优化MySQL NOT IN(查询

时间:2017-10-15 00:48:07

标签: mysql query-optimization notin

我正在尝试优化此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

提前谢谢。

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

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语句。