This is a theoretical question, I was wondering if there is a good way of finding out which condition in the WHERE statements matched.
Say I have a query like this:
SELECT * FROM table WHERE
COND1 OR
(COND2 AND COND3) OR
COND4
Is there any way of knowing which of the conditions made a given row match (or unmatch)?
One solution i thought of was adding a CASE clause, to the SELECT, and rerunning all the WHERE conditions for that row:
SELECT *, which_cond = CASE .... END CASE ...
CASEis a possibility. But shorter to write would beIF()(at least with MySQL):and every
cond*matched if its value is1.Of course it does not make sense to check whether
COND1matches or not. For all results you get back,COND1was true. SoIF(COND1, 1, 0)will always return1(in your example).Update:
Again at least for MySQL, I discovered, that the following is sufficient if you only want to get either
1or0as result:and with respect to Mark’s answer, you can avoid writing the conditions twice, if you use
HAVINGinstead ofWHERE(HAVINGas access to aliases):(note: uppercase means the actual condition expression and lowercase is the alias name)
Update 2:
Well it changes not that much: you only have to check conditions that are connected via
ORin your updated version it would be sufficient to check whetherCOND2is true or not. If so, thenCOND3is also true and vice versa.I think the point is clear.