SQL Server 2012 - 如果条目不在 table B 中,则尝试使用 JOIN 更新 table A 中的值

SQL Server 2012 - Trying to Update value in table A if entry is not in table B using a JOIN

下面的 UPDATE 语句完全符合我的要求:

UPDATE [dbo].[Person]
SET [IsUpdated] = 0 
FROM [Person] p
WHERE p.IsUpdated = 1
  and p.PersonID NOT IN (SELECT DISTINCT q.PersonID FROM [DeletionQueue] d, [Queue] q
                         WHERE d.fkQueueID = q.QueueID)

但是,当我 运行 此语句的估计执行计划时,我发现 70% 的处理时间被 NOT IN SELECT 语句消耗。我更愿意使用某种 JOIN 语句获得相同的结果。

我曾尝试以多种不同的方式创建声明,但我能够复制上述声明的最接近结果是给出与我正在寻找的结果完全相反的结果(即如果我在 IsUpdated = 1 的 Persons table 中有 2 个人,则两个人在 Queue table (QueueID) 中都有一个条目,但只有 B 在 DeletionQueue table (fkQueueID ), 那么只有 A 在 Person table 中的记录应该将 IsUpdated 更改为 0)。目前,当我尝试 JOIN 语句时,B 已更新,而 A 未更新。

如有必要,我可以按原样使用该语句,但性能在此应用程序中非常关键。有什么想法吗?

您可以尝试使用 NOT EXISTS 代替:

UPDATE [dbo].[Person]
    SET [IsUpdated] = 0 
FROM [Person] p
WHERE
    p.IsUpdated = 1
    AND NOT EXISTS(
        SELECT 1
        FROM [DeletionQueue] d
        INNER JOIN [Queue] q
            ON q.fkQueueID = q.QueueID
        WHERE q.PersonId = p.PersonId
    )

根据 Aaron Bertrand 的 article

for the pattern of finding all rows in table A where some condition does not exist in table B, NOT EXISTS is typically going to be your best choice. But, as always, you need to test these patterns in your own environment, using your schema, data and hardware, and mixed in with your own workloads.