首页 > 解决方案 > 如何加快 NOT IN 查询?

问题描述

我有以下查询:

SELECT images.id from images WHERE images.id NOT IN
(
    SELECT
        temp.target_id

    FROM (
        SELECT
            images_user_groups.images_id AS target_id,
            images_user_groups.user_groups_id AS source_id

        FROM
            images_user_groups
    ) AS temp

        INNER JOIN
        user_groups ON user_groups.id = temp.source_id
    INNER JOIN
        images ON images.id = temp.target_id
    WHERE
        user_groups.description LIKE "%Freigabe ins Presseportal%"
    GROUP BY
        temp.target_id
)

它运行,但运行速度非常慢—— 5 分钟,在我写这篇文章时还在数。(我正在运行的子查询NOT IN返回 36,000 行,我假设父查询需要时间来检查表中的 38,000 个条目中的每一个条目images与这 36,000 行。)

有没有办法可以加快这个查询?

标签: mysql

解决方案


将其写为应该快得多LEFT JOIN,在 中查找NULLuser_groups以指示图像不在该组中:

SELECT i.id 
FROM images i
JOIN images_user_groups iu ON iu.images_id = i.id
LEFT JOIN user_groups u ON u.id = iu.user_groups_id AND u.description LIKE "%Freigabe ins Presseportal%"
GROUP BY i.id
HAVING COUNT(u.id) = 0

NOT INand的问题NOT EXISTSWHERE必须对images.


推荐阅读