在右表中获取带有条件的所有数据左表(ms sql)

时间:2013-01-23 14:55:36

标签: sql-server sql-server-2008 sql-server-2005

colA colB -------------------------------- tab_1
1 AA
2 BB
3 CC
4 DD
5 EE

colA colC ------------------------------- tab_2
1 XX
2 YY
3 ZZ

输出必须(tab_2.colC!= ZZ)

colA colB colC
1 AA XX
2 BB YY
4 DD NULL
5 EE NULL

我尝试使用左连接但它将返回所有5条记录

例如:

select tab_1.colA, tab_1.colB, tab_2.colC
from tab_1
left join tab_2 on tab_1.colA = tab_2.colA and tab_2.colC != 'ZZ'

如果有人可以帮助我,我真的很感激吗?

3 个答案:

答案 0 :(得分:2)

SELECT
T1.colA, T1.colB, T2.olC
FROM tab_1 T1
  LEFT JOIN tab_2 T2
    ON T1.colA = T2.colA
WHERE T2.colC != 'ZZ'
   OR T2.colC IS NULL

答案 1 :(得分:0)

SELECT  a.*, b.ColC
FROM    table1 a
        LEFT JOIN table2 b
            ON a.ColA = b.ColA
WHERE   b.colC <> 'zz' OR b.ColC IS NULL

答案 2 :(得分:0)

SELECT t1.colA, t1.colB, t2.colC
FROM tab_1 t1
LEFT JOIN tab_2 t2
ON tab_1.colA = tab_2.colA
WHERE t2.ColC <> 'ZZ' OR t2.ColC IS NULL