开发者

Better way to write a SQL query with many ORs

开发者 https://www.devze.com 2023-04-11 23:57 出处:网络
I\'ve a list or category of colors. Category: Red, Blue, Green, ... //At least 9 for one category 开发者_StackOverflow社区

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 ids 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 ORs.

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')
0

精彩评论

暂无评论...
验证码 换一张
取 消