删除多个子 SQL 服务器后从父 table 删除行

Delete rows from parent table after deleting multiple children SQL Server

我有一个 table 在另外 4 个 table 中有外键。我删除了子项 table 中的行,为了从父项中删除,我在不存在的地方进行了查询,因为我已经删除了引用。但我在编写查询时仍然遇到问题,因为它 returns 是一个空结果集。

我相信我做错了什么。

这是我的查询

select *
from paretntable 
where parentID not in (select i.ParentID 
                       from child1 i 
                       left join child2 m on i.parentID = m.parentID) 
  and not exists (select ac.parentID 
                  from child3 ac 
                  left join child4 d on ac.parentID = d.parentID)

我就是这样做的,左连接到所有 children 然后检查它们是否都是空的(在这种情况下我使用 coalesce 这样做。)这是非常有效和使用您在表中设置的所有索引。它没有任何 sub-queries.

select *
from paretntable p
left join child1 i on p.parentID =  i.parentID
left join child2 m on p.parentID =  m.parentID
left join child3 ac on p.parentID =  ac.parentID
left join child4 d on p.parentID =  d.parentID
where coalesce(i.parentID, m.parentID, ac.parenti, d.parentID) is null
so, I set up two tables... ParentTable with a key of ParentID, 
and ChildTable, key of ChildID and FK of ParentID.


delete dbo.parenttable
where parentid = 3
-- produces error because rows exist in dbo.childtable where parentid = 3

delete dbo.childtable 
where parentid = 3
-- deletes all rows in dbo.childtable where parentid = 3

-- Assuming This is where you are now
--- .... needing to find all rows in parent table 
---      where there are no corresponding child 
---      rows in dbo.childtable


with CTE_Parent as          --wrap up the selected ID's in a CTE expression
(select dbo.parenttable.parentid
from dbo.parenttable
left outer join dbo.childtable 
on dbo.parenttable.parentid = dbo.childtable.parentid   
where dbo.childtable.parentid is null  --- trick to find non-existent child recs
)

delete dbo.parenttable
from dbo.parenttable
inner join cte_Parent
on dbo.parenttable.parentid = cte_parent.parentid