MySQL, Short WHERE query
Here is my example query.
SELECT * FROM `table` WHERE `id` = '1' OR `id` = '8' OR `id` = '12'
Is there a quicker way for WHERE part开发者_如何学JAVA?
You could use the IN clause:
SELECT *
FROM `table`
WHERE `id` IN ('1', '8','12')
Since the query optimizer will convert this query into an execution plan which will be very similar to the sequence of ORs it won't really make a performance difference. It's about aesthetics and/or less typing :)
Not sure if it runs faster, but it may read more cleanly:
SELECT * ... WHERE ID in ('1', '8', '12' )
To check for multiple potential values in a where clause for the same field, you need to use IN
.
In your example, you would use:
SELECT *
FROM `table`
WHERE `id` IN (1, 8, 12)
This feature is also useful for using subqueries, such as:
SELECT *
FROM `table`
WHERE `id` IN (
SELECT `id`
FROM `table2`
)
精彩评论