这是我的数据结构,我希望返回#ValuesDenied中不存在的#1的所有结果。我的第一个查询错误是由于它不知道#ValuesDenied。[sin]引用了什么。我的第二个查询知道前面的引用是什么,但是返回所有结果,即使我的左连接中应该排除其中的两个?
Create Table #1
(
ID int,
rsl varchar(100),
[sin] varchar(100),
teamname varchar(100)
)
Create Table #ValuesDenied
(
ID int,
originalID int,
rsl varchar(100),
[sin] varchar(100),
teamname varchar(100)
)
Insert Into #1 Values (1, 'MKX', 'Approved', 'Alpha'), (2, 'MKZ', 'Approved', 'Omega'), (3, 'RMN', 'Approved', 'Delta')
INSERT INTO #ValuesDenied VALUES (200, 1, 'MKX', 'Manager Denied', 'Alpha'), (400, 2, 'MKZ', 'Supervisor Returned', 'Omega')
Select #1.ID, #1.[sin], #1.teamname, #ValuesDenied.[sin]
FROM #1
WHERE #1.ID NOT IN (Select originalID FROM #ValuesDenied)
AND #1.[sin] = 'Approved'
Select #1.ID, #1.[sin], #1.teamname, #ValuesDenied.[sin]
FROM #1
LEFT JOIN #ValuesDenied
ON #1.ID = #ValuesDenied.originalID
WHERE #1.[sin] = 'Approved'
答案 0 :(得分:0)
第一个查询错误,因为您引用了未知列#ValuesDenied.[sin]
。您是从#1
表中选择而不是#ValueDenied
。你应该删除它。
Select #1.ID, #1.[sin], #1.teamname
FROM #1
WHERE
#1.ID NOT IN (Select originalID FROM #ValuesDenied)
AND #1.[sin] = 'Approved'
第二个查询返回所有行,因为您没有过滤它们。您应在#ValuesDenied.originalID IS NULL
条款中添加WHERE
。
SELECT
#1.*
FROM #1
LEFT JOIN #ValuesDenied
ON #1.ID = #ValuesDenied.originalID
WHERE
#1.sin = 'Approved'
AND #ValuesDenied.originalID IS NULL
<强> RESULT 强>
ID rsl sin teamname
----------- ------- ---------- -----------
3 RMN Approved Delta