【问题标题】:Delete all records in table which have no reference in another table删除表中所有在另一个表中没有引用的记录
【发布时间】:2016-12-18 11:59:11
【问题描述】:

我有一张名为Document 的表。

文档

id int
docuid int
doc blob

然后我有两个引用表

AppRequiredDocuments

id int
appid int
docid int -> references document -> id

AppDocuments

id int
appid int
docid int -> references document -> id

由于文档表中的一个非常旧的迁移孤立项,我必须引用其他表中的引用。如何仅删除文档表中AppDocumentsAppRequriedDocuments中未引用的文档?

【问题讨论】:

    标签: sql sql-server tsql sql-delete


    【解决方案1】:

    一种方法使用删除连接:

    DELETE d
    FROM Document d
    LEFT JOIN AppRequiredDocuments t1
      ON d.id = t1.docid
    LEFT JOIN AppDocuments t2
      ON d.id = t2.docid
    WHERE t1.docid IS NULL AND
          t2.docid IS NULL
    

    这里的逻辑是,如果给定的Document 记录没有被两个辅助表中的anything 引用,那么在连接的结果集中为另外两个表添加docid 列表应该NULL

    【讨论】:

    • 您可能需要LEFT OUTER JOIN 来获取关联表中不存在 的那些行......使用INNER JOIN;这些行甚至不会出现在结果集中.....
    【解决方案2】:

    您可以使用 union [all] 运算符生成单列引用,然后对其进行检查,例如,使用 [not] exists 运算符:

    DELETE FROM Document d
    WHERE  NOT EXISTS (SELECT *
                       FROM   AppRequiredDocuments ard
                       WHERE  ard.docid = d.id
                       UNION ALL
                       SELECT *
                       FROM   AppDocuments ad
                       WHERE  ad.docid = d.id)
    

    【讨论】:

      【解决方案3】:

      您可以使用NOT EXISTS 查找和删除这些项目:

      delete from document d
      where not exists (select 1 from AppRequiredDocuments a where a.docid = d.id);
      and not exists (select 1 from AppDocuments a where a.docid = d.id);
      

      【讨论】:

      • 忘记了别名。请立即尝试?
      猜你喜欢
      • 1970-01-01
      • 2010-09-21
      • 2013-04-04
      • 1970-01-01
      • 1970-01-01
      • 2013-08-18
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      相关资源
      最近更新 更多