The examples you posted may not be what the user intends. As I said, you can
NOT automatically generate the parentheses because there is no way for you to know the intention of the user. It is better to give the user a warning whenever both AND and OR are used that he needs to include parentheses in order to control the order of precedence. The best you could do if there are NO parentheses specified is to add them based on the rules for the order of precedence - which is NOT what you did above. Applying the order of precedence programmatically REQUIRES that you understand all the nuances and is not a trivial programming task since it involves recursion.
An alternate interpretation for sample 1 is:
Cr1 or
( Cr2 and Cr3 and Cr4
)
An alternate interpretation for sample 2 is:
( Cr1 and Cr2
) or
( Cr3 and Cr4
)
It is important if you program to know this stuff.
Operator precedence determines how operators are parsed concerning each other. Operators with higher precedence become the operands of operators with lower precedence.
()
NOT
AND
OR
So the DEFAULT interpretation of: Cr1 or Cr2 and Cr3 and Cr4 ==== Cr1 or
( Cr2 and
( Cr3 and Cr4
)) ---- The innermost pair is Cr3 and Cr4, then that expression is AND'd with Cr2, and the whole expression is OR'd with Cr1. This should give you a clue why the Access QBE goes hog-wild with parentheses. It is using boolean logic to construct the expressions and doesn't try to simplify them to get rid of the extraneous pairs when it is done.
The default for Cr1 and Cr2 or Cr3 and Cr4
Is ( Cr1 and Cr2 ) or ( Cr3 and Cr4 ) ------ Each pair of AND's is created and the two expressions are OR'd
Consider how NOT works with and without parentheses.
Cr1 or Cr2 and not Cr3 and Cr4 ====
( Cr1 or Cr2
) and
( not
( Cr3
) and Cr4
)
It is quite possible, the user actually wanted ----
( Cr1 or Cr2
) and not
( Cr3 and Cr4
)
If the starting expression includes (), the expressions inside each set of parentheses is evaluated and may result in additional parentheses being added.
Here's the best example I came up with explaining how evaluation actually works. It is for math but the principle is the same for boolean operations. Watch carefully to see what ends up as the operands for the division.