为什么这个MYSQL在查询中这么慢?

时间:2018-02-15 00:15:26

标签: mysql sql

我有一个查询,检查另一个表,看看是否有电子邮件在那里,并匹配其他条件。然而,只需要10k行就需要很长时间。一切都正确索引。我假设NOT IN子查询只运行一次?有没有更好的方法来写这个?

SELECT
    COUNT(*) AS `numrows`
FROM
    (
        SELECT
            COUNT(end_users.email)
        FROM
            `end_users`
        WHERE
            `email` NOT IN (
                SELECT
                    email
                FROM
                    email_que
                WHERE
                    email_cronjob_id IN (1, 2)
            )
    ) count_results

2 个答案:

答案 0 :(得分:0)

您可以重写避免NOT IN

的sql
SELECT
    COUNT(*) AS numrows
FROM
    (
        SELECT
            COUNT(eu.email)
        FROM
            end_users eu
        WHERE
         NOT   EXISTS   (
                SELECT
                    email
                FROM
                    email_que eq
                WHERE
                    eq.email_cronjob_id IN (1,2)  AND eu.email  =  eq.email
            )
    ) count_results

答案 1 :(得分:-1)

也许您可以尝试使用LEFT JOIN代替NOT IN子查询。

SELECT
    COUNT(*) AS `numrows`
FROM
(
    SELECT
        COUNT(t1.email) 
    FROM 
        `end_users` AS t1
    LEFT JOIN
        `email_que` AS t2 ON t1.email = t2.email AND t2.email IS NULL
    WHERE 
        t2.email_cronjob_id IN (1,2)
) count_results