通过这篇出色的帖子https://stackoverflow.com/a/9755787/9502397,我现在更好地了解了如何使用Join返回具有不同表中相似引用的结果列表。
运行Select查询后,我将得到结果列表所示的列表
select
a.OrderDate,
c.StaffID,
c.Activate
from
tbl_Order a
join tbl_OrderDetails b
on a.OrderID = b.OrderID
join tbl_Staff c
on b.StaffID = c.StaffID
where c.Activate = 'False'
但是,如何使用该结果列表并从tbl_Order中删除这些行?
答案 0 :(得分:0)
如有疑问,请使用exists
:
delete
from tbl_order a
where exists
(
select 1
from tbl_OrderDetails b
inner join tbl_staff c
on b.StaffID = c.StaffID
and c.Activate = 'False'
where b.Order_id = a.Order_id
)
答案 1 :(得分:0)
您还可以使用通用表表达式来分隔对结果集的查询,并删除结果集和所需表中存在的数据:
WITH cte AS
(
select
a.OrderDate,
c.StaffID,
c.Activate
from
tbl_Order a
join tbl_OrderDetails b
on a.OrderID = b.OrderID
join tbl_Staff c
on b.StaffID = c.StaffID
where c.Activate = 'False'
)
Delete
FROM cte t1
INNER JOIN tbl_Order t2
ON t1.Order_id = t2.Order_id;
答案 2 :(得分:0)
您可以使用DELETE FROM WHERE ()IN ()
表单,这是代码中的样子:
DELETE FROM
tbl_Order k
WHERE (k.OrderID) IN (
SELECT
a.OrderID
FROM
tbl_Order a
JOIN tbl_OrderDetails b
ON a.OrderID = b.OrderID
JOIN tbl_Staff c
ON b.StaffID = c.StaffID
WHERE c.Activate = 'False' )
使用SELECT提取要删除的OrderID时,DELETE的WHERE仅选择具有要删除的ID的行。
答案 3 :(得分:0)
您可以在DELETE中使用JOIN,就像使用SELECT一样。只需确保“删除”中的别名来自您要从中删除数据的表即可。
DELETE a
FROM
tbl_Order a
INNER JOIN tbl_OrderDetails b
on a.OrderID = b.OrderID
INNER JOIN tbl_Staff c
on b.StaffID = c.StaffID
WHERE c.Activate = 'False'