优化 MySQL NOT IN( 查询

Optimizing a MySQL NOT IN( query

我正在尝试优化此 MySQL 查询。我想计算在查看当前约会之前没有约会的客户数量。换句话说,如果他们有约会(这是 NOT IN( 子查询正在检查的内容),则将他们排除在外。

但是,此查询绝对会降低性能。我知道 MySQL 对于 NOT IN( 查询不是很好,但我不确定优化此查询的最佳方法。它需要 15 到 30 秒到 运行。我已在 CustNo、AptStatus 和 AptNum 上创建索引。

SELECT
        COUNT(*)             AS NumOfCustomersWithPriorAppointment,
FROM 
        transaction_log AS tl
LEFT JOIN
        appointment AS a
ON
        a.AptNum = tl.AptNum
INNER JOIN
        customer AS c
ON
        c.CustNo = tl.CustNo
WHERE
        a.AptStatus  IN (2)
AND     a.CustNo NOT IN
        (
                SELECT
                        a2.CustNo
                FROM
                        appointment a2
                WHERE
                        a2.AptDateTime < a.AptDateTime)


AND     a.AptDateTime > BEGIN_QUERY_DATE
AND     a.AptDateTime < END_QUERY_DATE

提前致谢。

尝试以下操作:

SELECT
        COUNT(*)             AS NumOfCustomersWithPriorAppointment,
FROM 
        transaction_log AS tl
INNER JOIN
        appointment AS a
ON
        a.AptNum = tl.AptNum
LEFT OUTER JOIN appointment AS earlier_a
        ON earlier_a.CustNo = a.CustNo
        AND earlier_a.AptDateTime < a.AptDateTime
INNER JOIN
        customer AS c
ON
        c.CustNo = tl.CustNo
WHERE
        a.AptStatus  IN (2)
AND     earlier_a.AptNum IS NULL


AND     a.AptDateTime > BEGIN_QUERY_DATE
AND     a.AptDateTime < END_QUERY_DATE

这将受益于 (CustNo,AptDateTime) 上的综合索引。如果符合您的业务模型,请使其独一无二(从逻辑上讲,它似乎应该如此,但实际上可能并非如此,具体取决于您如何处理应用程序中的冲突。)

如果这不能带来足够的性能改进,请为所有表提供 SHOW CREATE TABLE 语句。