如何提高查询NOT IN的性能

VAA*_*AAA 4 sql t-sql sql-server performance notin

我有以下SQL查询.

SELECT em.employeeid, tsi.timestamp
FROM timesheet_temp_import tsi
JOIN employee emp ON emp.employeeid = tsi.credentialnumber
WHERE
tsi.masterentity = 'MASTER' AND
tsi.timestamp NOT IN
(
    SELECT ea.timestamp 
    FROM employee_attendance ea 
    WHERE 
    ea.employeeid = em.employeeid
    AND ea.timestamp =  tsi.timestamp
    AND ea.ismanual = 0
)
GROUP BY em.employeeid, tsi.timestamp
Run Code Online (Sandbox Code Playgroud)

此查询比较导入表(具有员工时间和出勤时间戳).

有时候timesheet_temp_import有超过95,000行,我的查询显示员工的时间戳.如果员工已经存在时间戳,那么我必须将其排除.

查询正在运行,但是花了4分多钟,所以我想知道我是否可以改进NOT IN其他语句,这可以帮助我减少这段时间.

Luc*_*c M 6

使用NOT EXISTS可能会帮助你.

SELECT 
    em.employeeid,
    tsi.timestamp
    FROM timesheet_temp_import tsi
    join employee emp ON emp.employeeid = tsi.credentialnumber
    WHERE
    tsi.masterentity = 'MASTER' AND

    NOT EXISTS 
    (
        SELECT NULL  
        FROM employee_attendance ea 
        WHERE 
        ea.employeeid = em.employeeid
        AND ea.timestamp =  tsi.timestamp
        AND ea.ismanual = 0
    )
    GROUP BY 
    em.employeeid,
    tsi.timestamp
Run Code Online (Sandbox Code Playgroud)

  • @JohnOdom [不存在vs不存在vs左连接](http://explainextended.com/2009/09/15/not-in-vs-not-exists-vs-left-join-is-null-sql-server /) (2认同)