开发者

MySQL query optimization: IN() vs OR

I've been reading, that MySQL has a problem with queries that use IN() statement - sometimes indexes can't be used. Is that really so, if I don't use a subquery?

Which approach is better? Is there a performance difference?

1

开发者_运维百科
SELECT *
FORM `somewhere`
WHERE 
  `id` = 3
   OR `id` = 5
   OR `id` = 15
   OR `id` = 56
   OR `id` = 34
   OR `id` = 47

2

SELECT *
FORM `somewhere`
WHERE 
  `id` IN (3,5,15,56,34,47)


The second approach is better. MySQL can optimize this.

MySQL has a problem with queries that use IN() statement - sometimes indexes can't be used. Is that really so, if I don't use a subquery?

There can be a problem with IN when you write IN(SELECT ...), but I don't think there is a problem with a simple list of values.


If you really want to use indexes you can use UNION read more here mysql-followup-on-union-for-query-optimization-query-profiling

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜