简体   繁体   English

使用IN()时主索引不起作用吗?

[英]Does primary index not work when using IN()?

SELECT 
  i.id 
FROM 
  itable i
WHERE 
  i.id IN (
    SELECT 
      itable_id j 
    FROM 
      ijoin j 
    WHERE 
      j.user_id = '1'
  )

This query examines every single row on itable, which is about 3 million. 此查询检查itable上的每一行,大约300万行。 Since i.id is the PRIMARY KEY, shouldn't it just fetch those items? 由于i.id是主键,因此它不应该仅获取那些项吗?

How can I optimize this query? 如何优化此查询?

MySQL is notoriously poor at optimizing this type of query. 众所周知,MySQL在优化此类查询方面很差。 Instead of selecting the small number of values in the subquery and using them to index into the main table, it iterates through all the rows in the main query and uses them to index into the table in the subquery. 而不是在子查询中选择少量的值并使用它们索引到主表中,而是迭代遍历主查询中的所有行,并使用它们在子查询中索引到表中。

It does better if you use a JOIN : 如果使用JOIN会更好:

SELECT DISTINCT i.id
FROM itable i
JOIN ijoin j ON i.id = j.itable_id
WHERE j.user_id = '1'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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