I’ve got a query like:
SELECT * FROM table WHERE id=1 AND (field1=1 OR field2=1 OR field3=1 OR field4=1 OR field5=1 OR field6=1 OR field7=1 OR field8=1)
The actual query is longer and there are more than 25 fields in the brackets…
How would I make sure that at least two of the fields = 1? If those were rows it would be easy, but what about columns? Not sure if it’s even possible.
Basically I need to run a php function only if there are at least two matching fields. The function then updates the selected fields so that they will not be selected again next time.
In MySQL, conditional statements can be evaluated directly, and they return “1” if they are true and “0” if they are false. So in this case, you can just sum the conditionals like so:
If the sum is equal to or greater than 2 then at least two fields have the value “1”. Note that you must put parenthesis around the conditionals here to make sure they are individually evaluated; otherwise it doesn’t parse correctly.
In the general case, there is also the MySQL’s IF function. You could use it here like this:
IF() takes three arguments. The first is a condition. The second is the return value if the condition is true. The third is the return value if the condition is false. So this would work too since in MySQl, the value of a bare conditional is equivalent to the value of
IF(conditional, 1, 0).