将Sql“Not In”更改为“Left Outer Join”

时间:2010-01-06 18:47:59

标签: sql-server tsql join

我不想在这个sql查询中使用“not in”。我该怎么做?感谢

SELECT  
 T2.Sno,
 T2.Name,
 T1.description,
 T2.UserCode            
FROM 
 Table1 AS T1 (nolock)
    INNER JOIN T2 (nolock)
    ON T1.UserCode = T2.UserCode
WHERE
 g.xid= @p_xid
 and T2.Sno not in (select Gid from T3 (nolock))

2 个答案:

答案 0 :(得分:6)

假设T2中没有行,其中Sno为空,而在T3中,Gid为空:

SELECT  
 T2.Sno,
 T2.Name,
 T1.description,
 T2.UserCode            
FROM 
 Table1 AS T1 WITH (nolock)
    INNER JOIN T2 WITH (nolock)
      LEFT JOIN T3 WITH (NOLOCK)
      ON T2.Sno = T3.Gid
    ON T1.UserCode = T2.UserCode
WHERE
 g.xid= @p_xid
 and T3.Gid IS NULL

答案 1 :(得分:2)

如果每个T2.Sno = T3.Gid有多个T3行,则需要在JOIN中使用DISTINCT。

  • 没有DISTINCT,这是一个不同的查询
  • 使用DISTINCT,这是一个额外的步骤。

我会使用NOT EXISTS来避免这种情况。

SELECT  
 T2.Sno,
 T2.Name,
 T1.description,
 T2.UserCode            

FROM 
 Table1 AS T1 (nolock)
    INNER JOIN T2 (nolock)
    ON T1.UserCode = T2.UserCode
WHERE
 g.xid= @p_xid
 and not exists (select * from T3 (nolock) where T3.Gid = T2.Sno)