主表:
MasterID | PartID
1 1
2 3
3 5
部分表:
PartID | PartName | DeleteDate
1 Part1 NULL
2 Part2 NULL
4 Part4 NULL
5 Part5 08-04-2017
结果表:
MasterID | PartID
2 3
3 5
这两个表存在于两个不同的数据库中,如果Master表中PartID
不在Part表中且Master表中有任何PartID
,我需要使用SQL查询进行验证以获取记录在Part表中删除(即DeleteDate
IS NOT NULL)
我正在尝试使用以下查询,但未获得预期结果
Select
*
FROM DBNAME.DBO.Master
Where PartID in (
Select
PartID
from Part)
and PartID not in (
Select
PartID
from Part
where DeleteDate is NOT NULL)
请让我知道如何实现这个目标
答案 0 :(得分:3)
一种方法是LEFT JOIN
Master
表到Part
表,然后保留未映射到Part
表中的任何内容或映射的任何部分删除部分。
SELECT
m.PartID,
CASE WHEN p.partID IS NULL THEN 'missing' ELSE 'deleted' END AS status
FROM Master m
LEFT JOIN Part p
ON m.PartID = p.PartID
WHERE
p.PartID IS NULL OR -- missing part
p.DeleteDate IS NOT NULL -- deleted (but present) part
答案 1 :(得分:0)
作为替代方式,您可以在两种情况下使用union
Select
t1.*
From
DBNAME.DBO.Master t1,Part t2
Where
t1.PartID = t2.PartID(+) and t2.PartID is null
Union All
Select
t1.*
From
DBNAME.DBO.Master t1,Part t2
Where
t1.PartID = t2.PartID and t2.DeleteDate is not null;