使用“NOT IN”运算符转换子查询以与多个表连接

时间:2014-01-03 17:12:08

标签: sql sql-server join subquery

我需要将以下子查询转换为JOIN。这里我在内部查询中已经有了JOIN运算符。请帮忙。

SELECT * 
FROM   Consultants 
WHERE  Consultants.ConsIntID 
NOT IN  (SELECT Links.ToID 
         FROM   Links JOIN Reminders 
         ON Links.FromID = Reminders.RemIntID 
            AND ApptSubType = 'Placed' 
            AND ToID LIKE 'CS%') 

2 个答案:

答案 0 :(得分:5)

好的,所以你可能不应该把它更改为我会使用NOT EXISTS的联接,这样做的理由是here

我还替换了您的古老连接语法并添加了别名来清除它。下面显示的方法已经被接受了大约22年的标准,并且是preferred编写查询的方法。

SELECT C.* 
FROM   Consultants  as C -- aliases are very useful for clarity
WHERE  
NOT EXISTS (
        SELECT 1
         FROM   Links as L 
         INNER JOIN Reminders  as R --New join syntax
            ON  L.FromID = R.RemIntID 
         WHERE C.ConsIntID = L.ToID 
         AND ApptSubType = 'Placed' 
         AND ToID LIKE 'CS%'
            ) 

答案 1 :(得分:0)

SELECT * 
FROM   Consultants 
WHERE  Consultants.ConsIntID 
NOT IN  (SELECT Links.ToID 
         FROM   Links 
         JOIN   Reminders  ON(Links.FromID = Reminders.RemIntID)
         WHERE  ApptSubType = 'Placed' 
                AND ToID LIKE 'CS%')