在SQL数据库中,如果已从Table_A中删除匹配的ID,如何从Table_B中删除记录?

时间:2015-01-26 16:38:20

标签: sql-server

我有两张桌子Table_A& Table_B其中Table_B.IX_Id = Table_A.IX_ID。这些表中的记录如下所示:

QUERY:

   select * from Table_A where IX_ID = 4783 
   select * from Table_B where IX_Id = 4783 

结果:

Table_A result

IX_ID       IX_ParentID          IX_CreationDate
----------- -------------------- --------------------
4783        0                    2015-01-26 10:23:00

Table_B result    

IX_Id       Row_Id      Document_Id
----------- ----------- -----------
4783        1           101 
4783        1           99
4783        1           94

现在让我们说我删除了Table_A的记录,这个记录是我想要的4783,还删除了Table_B中记录为id为4783的记录。

我可以通过以下查询从Table_A获取已删除的记录:

QUERY:

;WITH Missing (missnum, maxid)
AS
(
 SELECT 1 AS missnum, (select max(IX_ID) from Table_A)
 UNION ALL
 SELECT missnum + 1, maxid FROM Missing
 WHERE missnum < maxid
)
SELECT missnum
FROM Missing
LEFT OUTER JOIN Table_A missingIds on missingIds.IX_ID = Missing.missnum
WHERE missingIds.IX_ID is NULL  order by 1 desc
OPTION (MAXRECURSION 0);

结果:

missnum
-----------
4783

预期结果:

检查missnum中是否存在Table_B,而不是从Table_B删除那些匹配的记录。我怎样才能做到这一点?

注意:我从Table_A删除了很多记录,我正在Table_B进行调整,其中相应的记录数百个。

2 个答案:

答案 0 :(得分:3)

您可以使用NOT IN查找与子查询不匹配的内容,这样更简单,查询优化程序更有可能选择符合性能的内容

DELETE FROM Table_B
WHERE IX_Id NOT IN (SELECT IX_Id FROM Table_A)

我同意Will关于外键的评论,如果你想将Table_B中的IX_Id与Table_A保持一致

答案 1 :(得分:2)

拿这个:

;WITH Missing (missnum, maxid)
AS
(
 SELECT 1 AS missnum, (select max(IX_ID) from Table_A)
 UNION ALL
 SELECT missnum + 1, maxid FROM Missing
 WHERE missnum < maxid
)
SELECT missnum
FROM Missing
LEFT OUTER JOIN Table_A missingIds on missingIds.IX_ID = Missing.missnum
WHERE missingIds.IX_ID is NULL  order by 1 desc
OPTION (MAXRECURSION 0);

将其改为:

;WITH Missing (missnum, maxid)
AS
(
 SELECT 1 AS missnum, (select max(IX_ID) from Table_A)
 UNION ALL
 SELECT missnum + 1, maxid FROM Missing
 WHERE missnum < maxid
)
, Missing1 (missnum)
AS
(
 SELECT missnum
 FROM Missing
 LEFT OUTER JOIN Table_A missingIds on missingIds.IX_ID = Missing.missnum
 WHERE missingIds.IX_ID is NULL
)
DELETE FROM Table_B
WHERE IS_Id IN(SELECT missnum FROM Missing1)
OPTION (MAXRECURSION 0);