简体   繁体   中英

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

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

eg

SELECT * 
FROM   myTable
WHERE  color IN ('Red', 'Blue')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM