我不想在这个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))
答案 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。
我会使用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)