【问题标题】:Delete rows from parent table after deleting multiple children SQL Server删除多个子 SQL Server 后从父表中删除行
【发布时间】:2023-03-04 04:32:01
【问题描述】:

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

我认为我做错了什么。

这是我的查询

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)

【问题讨论】:

  • 如果您要删除子级以删除父级,为什么不启用级联并删除父级?

标签: sql sql-server stored-procedures not-exists notin


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    我就是这样做的,让所有子节点加入,然后检查它们是否都为空(在这种情况下,我使用 coalesce 来执行此操作。)这非常有效,并且使用了您设置的所有索引在你的桌子上。它没有任何子查询。

    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
    

    【讨论】:

      猜你喜欢
      • 2021-12-09
      • 2020-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-23
      • 2018-03-12
      • 1970-01-01
      相关资源
      最近更新 更多