MySQL,查询 "NOT IN ( SELECT ... )"非常慢

标签 mysql sql query-optimization

这是运行超过 10 分钟的查询。

SELECT *
FROM tableA
WHERE name NOT IN(
SELECT a.name
FROM tableA a
INNER JOIN tableB b ON a.code = b.code 
INNER JOIN tableC c ON c.number = b.number 
INNER JOIN tableD d ON d.code = b.code 
INNER JOIN tableE e ON e.content= d.content)

是否有替代查询运行得更快或有任何解决方案?非常感谢。

最佳答案

如果有适当的索引,您的查询应该可以正常工作。您也许可以尝试使用左连接。

select a.*
from tableA a
left join (
    select distinct a.name
    from tableA a
    inner join tableB b on a.code = b.code
    inner join tableC c on c.number = b.number
    inner join tableD d on d.code = b.code
    inner join tableE e on e.content = d.content
    ) b on a.name = b.name
where b.name is null;

性能主要取决于索引。 对于性能,我建议使用以下索引:

create index idx_tablea_code_name    on tableA(code, name);
create index idx_tableb_code_number  on tableB(code, number);
create index idx_tablec_number       on tableC(number);
create index idx_tabled_code_content on tableD(code, content);
create index idx_tablee_content      on tableE(content);

关于MySQL,查询 "NOT IN ( SELECT ... )"非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43176216/

相关文章:

SQL 优化 - 执行计划根据约束值更改 - 为什么?

mysql - LIMIT 0,1 会加速主键上的 SELECT 吗?

mysql - 文本字段

php - 卡纳达语单词在 Firefox 浏览器中显示为问号

sql - 插入插入的id到另一个表

sql - SSIS 字符串变量大小

mysql - 带有 SQL 注入(inject)的存储过程

php - 如何在sql中连接来自不同表的两个字段

mysql - 添加一个新的 MySQL Col,其行依赖于其他行

Android sqlite 和多个查询