I want to do a mysql query where data is retrieved from a database with some regulation.
I want to check which entries are similar to var1 or var2 or var3 and etc. AND are smaller than a given ID.
Like
SELECT *
FROM database
WHERE name = var1
OR name = var2
OR name = var3
AND id < 200
But the above line don't really works. Also when there is no more entry (which id is smaller than 200) it shows me however some entries.
Do you know what I mean? The query should select data which contains one of my wanted names AND which are smaller than an ID...
I have there a logic thinking problem...
解决方案
There is precedence with logical operators. When in doubt, use parenthesis.
In your case:
SELECT * FROM database WHERE (name = var1 OR name = var2 OR name = var3) AND id < 200
Your original query was interpreted as follows because the AND has higher precedence.
SELECT * FROM database WHERE name = var1 OR name = var2 OR (name = var3 AND id < 200)
Update
As commented by Rocket, you could condense your OR statements to IN since they operate on the same field. Doing so would remove the need for parentheses.
SELECT * FROM database WHERE name IN (var1,var2,var3) AND id < 200
Nonetheless, understanding the difference between the two original queries is important as you inevitably will write queries with multiple conditions.