Jump to content

MySQL using and or together


sonicthehedgehog

Recommended Posts

Sure. Also, you'll need to use parens around the ORs

WHERE (show=1 AND deleted=0 AND id=1) OR (id=2)
Edited by niche
Link to comment
Share on other sites

Just pay attention to what you're telling it to do. This:

WHERE (show=1 AND deleted=0 AND id=1) OR (id=2)
Will match either of these 2 conditions:
show = 1, deleted = 0, id = 1
or
id = 2
If that's not what you're trying to do, then rearrange the parentheses to group the conditions the way you want them.
Link to comment
Share on other sites

It sounds like show = 1 and deleted = 0 are always a requirement, so you would use an AND operator for them while the id is capable of changing.

 

If I understood your requirements, this is the logic you're looking for:

show = 1 AND deleted = 0 AND ( id = 1 OR id = 2 )
Link to comment
Share on other sites

You're right I only want some values to be set sometimes but others always. The trouble is there are around 75 different values that can be set as well as different combinations of those. So am I right in thinking that if I want some values to be set all of the time I keep them out of the brackets but if they may be part of the query then I add them to the bracket? Like this:

show = 1 AND deleted = 0 AND ( id = 1 OR id = 2 OR id = 3 ) AND name != ''
Link to comment
Share on other sites

Just write it so that it makes sense, pay attention to what you're telling the computer to do. If you have multiple conditions where any one of them could match and that's fine, then put all of them in parentheses with OR. The parentheses are there to group conditions, to make it explicit to the computer what you're asking for. If you know what you want it to do then you should be able to figure out how to group the different parts to achieve that.

Link to comment
Share on other sites

If it's a known range, then you can just use the BETWEEN operator

WHERE id BETWEEN 1 AND 75

If it's a known list of values, then you can use the IN operator

WHERE id IN (1, 2, 3, 4, 8, 12, 75)
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...