sql—两个独立的查询带有子查询的查询非常慢为什么?mysql/mariadb数据库

j2datikz  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(338)
DELETE FROM search WHERE sequence_id IN (34546);

受影响的行:0时间:0001秒

SELECT sequence_id FROM sequences WHERE sequence_status = 1;

正常时间:0001s

DELETE FROM search WHERE sequence_id IN (SELECT sequence_id FROM sequences WHERE sequence_status = 1);

受影响行:0时间:2868s
我做错什么了?

EXPLAIN DELETE FROM search WHERE sequence_id IN (SELECT sequence_id FROM sequences WHERE sequence_status = 1);

mzaanser

mzaanser1#

IN ( SELECT ... ) 是出了名的优化不好,尤其是在老版本的mysql/mariadb中。避开它!
复杂 DELETE / UPDATE 以前有一个蹩脚的解析器/优化器。我怀疑这是你打的。较新的版本统一了代码,从而改进了删除/更新的优化。
1ms的时间通常意味着查询缓存接管(因此,我不相信你的前两次计时。)
有多大 sequences ? 你有 INDEX(sequence_status, sequence_id) ?
给我多张table DELETE 语法一试,可能会有不同的优化。

eagi6jfj

eagi6jfj2#

尝试使用连接而不是 IN .

DELETE search
       FROM search
            INNER JOIN sequences
                       ON sequences.sequence_id = search.sequence_id
       WHERE sequences.sequence_status = 1;

要支持它,请在上创建索引 search (sequence_id) 以及 sequences (sequence_id, sequence_status) .

CREATE INDEX search_sequence_id
             ON search
                (sequence_id);

CREATE INDEX sequences_sequence_id_sequence_status
             ON sequences
                (sequence_id,
                 sequence_status);

相关问题