使用“not in”运算符转换子查询以加入

时间:2013-10-09 20:51:43

标签: sql-server join subquery

是否可以将带有NOT IN运算符的子查询转换为连接?我需要使用连接

的查询
SELECT *
FROM Contacts
WHERE ContactIntID NOT IN(
    SELECT LinkToIntID
    FROM Requirements
    WHERE Requirements.uuJobStatus = 'Open')

3 个答案:

答案 0 :(得分:12)

SELECT c.*
FROM Contacts c
LEFT JOIN 
  (SELECT LinkToIntID FROM Requirements WHERE uuJobStatus='Open') r 
  ON (c.ContactIntID=r.LinkToIntID)
WHERE r.LinkToIntID IS NULL

并简化:

SELECT c.*
FROM Contacts c
LEFT JOIN 
  Requirements r 
  ON  r.uuJobStatus = 'Open'
  AND c.ContactIntID = r.LinkToIntID
WHERE r.LinkToIntID IS NULL

答案 1 :(得分:3)

使用非存在通常比使用LEFT JOIN更好。有了上面的答案, 联系人将加入所有记录,无论它们是否匹配,然后使用IS NULL子句将其过滤掉。

SELECT *
FROM Contacts c
WHERE NOT EXISTS
(
    SELECT 1
    FROM Requirements r
    WHERE Requirements.uuJobStatus = 'Open'
    AND ContractIntID = r.LinkToIntID
)

编辑:意识到你想要一个非子查询,但值得注意我的回复:)

答案 2 :(得分:-1)

SELECT *
FROM Contacts C LEFT JOIN Requirements R
ON C.CommonField = R.CommonField
WHERE R.CommonField IS NULL AND R.uuJobStatus = 'Open'