问题
I have this line in my sql query:
WHERE client = $id
AND (isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1)
which gets more results than I am expecting. However, if I write it like this:
WHERE client = $id
AND (isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1 and client = $id)
then it gets me the results I wanted, but this is the best way to write this? I just don't want run into any more issues with this code.
回答1:
You need one more set of ()
around the entire AND
clause. This states that client = $id
MUST be true, and either of the other conditions must also me true = isinvoiced = 0
OR the combination of isinvoiced = 1 and isrecurring = 1
.
WHERE client = $id
AND ((isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1))
回答2:
Add a parenthesis around your AND
clause:
WHERE client = $id
AND ((isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1))
回答3:
where client = $id
and (
isinvoiced = 0
or (
isinvoiced = 1
and isrecurring = 1
)
)
回答4:
What you want is this:
WHERE client = $id AND ((isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1))
If you don't put the extra blaquets it will make an OR
with the client restiction and gives more results.
回答5:
As regards SQL, you should aim to write search conditions in conjunctive normal form ("a seires of AND
clauses"). There are various rewrite rules to assist in this.
The distributive rewrite law is useful in this case i.e.
( P AND Q ) OR R <=> ( P OR R ) AND ( Q OR R )
In your case:
( isinvoiced = 0 ) OR ( isinvoiced = 1 AND isrecurring = 1 )
may be rewritten as:
( isinvoiced = 0 OR isinvoiced = 1 ) AND ( isinvoiced = 0 OR isrecurring = 1 )
Therefore, the whole search condition without unwieldy parens:
....
WHERE client = $id
AND ( isinvoiced = 0 OR isinvoiced = 1 )
AND ( isinvoiced = 0 OR isrecurring = 1 );
回答6:
If you remove the initial where clause
remove -> WHERE client = $id
and just have
WHERE (isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1 and client = $id)
Does that get you the results you want?
来源:https://stackoverflow.com/questions/10283464/sql-query-where-clause