SQL Query查找2个表之间的匹配列组合

时间:2013-10-29 11:16:35

标签: sql

我想知道以下情况的查询。

Table 1 :         Table 2

Col1    Col2    Col1    Col2
Sandy    1     Sandy     24
Reena    2     Reena     32
Swathi   3     Swathi    3
Reenu    4     Karthik   5
               Reenu     4
               Muthu     6

查询应返回:

  1. 表2中不在表1中的行(Karthik和Muthu行应该是结果)

  2. 它应该比较列组合,并应返回更改的列组合。

  3. 最后我应该得到以下结果:

    Table1.Col1 Table1.col2 Table2.col2
    Sandy         1          24
    Reena         2          32
    Karthik      NA          5
    Muthu        NA          6
    

    提前致谢。

4 个答案:

答案 0 :(得分:1)

select t2.col1, t1.col2, t2.col2 as t2c
from table2 t2
left join table1 t1 on t1.Col1 = t2.Col1
where t1.Col2 is null or t1.Col2 <> t2.Col2

如果你想明确地'NA',你应该做这样的事情(功能取决于你的dbms)

coalesce(<somefunctionToConvertinttostring>(t1.col2), 'NA')

sqlFiddle

答案 1 :(得分:0)

请尝试:

select a.Col1, a.Col2, b.Col2 
from Table2 a left join Table1 b on a.Col1=b.Col1 
where b.Col1 is null

union

select a.Col1, a.Col2, b.Col2 
from Table2 a inner join Table1 b on a.Col1=b.Col1 
where a.Col2<>b.Col2

答案 2 :(得分:0)

您可以使用UNION ALL

连接两个查询
SELECT Table1.Col1 AS T1Col1, 
       Table2.col1 AS T2Col1, 
       Table2.col2 As T2Col2
FROM Table1 INNER JOIN Table2
  ON Table1.Col1 = Table2.Col1 
WHERE Table1.Col2 <> Table2.Col2

UNION ALL 

SELECT COALESCE(Table1.Col1,'NA') AS T1Col1, 
       Table2.col1 AS T2Col1, 
       Table2.col2 As T2Col2
FROM Table2 LEFT OUTER JOIN Table1
  ON Table1.Col1 = Table2.Col1 
WHERE Table1.Col1 IS NULL

Demonstration

答案 3 :(得分:0)

选择c3,ISNULL(C2,&#39; NA&#39;)AS C2,c4从表1右连接
表1上的表2 .c1 =表2.C3 WHERE ISNULL(Table1.c2,0)&lt;&gt; Table2.C4