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

时间:2017-04-03 03:47:57

标签: 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)

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

2 个答案:

答案 0 :(得分:3)

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

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);

答案 1 :(得分:0)

尝试不存在

SELECT *
FROM tableA t1
WHERE not exists (
SELECT 1
from tableB b
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
where t1.code = b.code

)