简化SQL删除查询

时间:2018-06-14 22:45:56

标签: sql-server

我有一个AuditAnswersTable,其中包含审计问题的答案,并且它具有与AuditTable相关的条目的id。

我现在想要删除没有提供答案的所有审核。我有这个工作查询,但我觉得必须有一个更简单的方法吗?

DELETE FROM AuditTable
WHERE id IN (
    SELECT id FROM AuditTable
    WHERE id NOT IN (
        SELECT DISTINCT audit_id
        FROM AuditAnswersTable
    )
)

2 个答案:

答案 0 :(得分:2)

您可以通过LEFT JOIN避免子选择:

DELETE a
FROM AuditTable a
    LEFT JOIN AuditAnswersTable t
        ON a.id = t.audit_id
WHERE t.audit_id IS NULL ;

答案 1 :(得分:0)

DELETE FROM AuditTable
WHERE id NOT IN (
    SELECT DISTINCT audit_id
    FROM AuditAnswersTable
)