Better way to write a SQL query with many ORs
I've a list or category of colors.
Category: Red, Blue, Green, ... //At least 9 for one category
开发者_StackOverflow社区
And my MySQL table has entries like:
id | color
-- | -----
1 | Red
2 | Black
3 | Green
4 | Purple
. .
. .
I want to get id
s which have color
from my category. They way I'm structuring my query right now is ... WHERE color = 'Red' OR color = 'Blue' OR ...
which would lead of a long (at least 9) list of OR
s.
I think I'm missing something. There must be a better way.
Use IN
. From the documentation:
expr IN (value,...)
Returns 1 if expr is equal to any of the values in the IN list, else returns 0.
Your query can be changed to this:
WHERE color IN ('Red', 'Blue', ... )
Try to use the keyword
IN
e.g.
SELECT *
FROM myTable
WHERE color IN ('Red', 'Blue')
精彩评论