2011-02-16 146 views
2

我需要一个查询来生成两个表格之间的比较表。使用SQL比较两个表格

事情是这样的:

TABLE_1:

col1 | col2 | col3 
a | 1 | a_comment 
b | 2 | b_comment 

TABLE_2:

col1 | col2 | col3 
a | 3 | a_comment 
c | 4 | c_comment 

查询结果:

col1 | table_1.col2 | table_2.col2 | col3 
a |  1  |  3  | a_comment 
b |  2  |  NULL  | b_comment 
c |  NULL  |  4  | c_comment 

另外,我需要保持秩序,S.T.如果col1中的x在col1中的任何一个表中的col1之前,它也将在查询结果之前。 我试图用FULL JOIN做它,但它重复col1和col3。

谢谢!

+0

如果table_1和table_2对于col3具有不同的值,会发生什么情况? – Matthew 2011-02-16 16:24:38

回答

4
select t1.col1, t1.col2, t2.col2, t1.col3 
    from table_1 t1 
     left join table_2 t2 
      on t1.col1 = t2.col1 
       and t1.col3 = t2.col3 
union 
select t2.col1, t2.col2, t1.col2, t2.col3 
    from table_2 t2 
     left join table_1 t1 
      on t2.col1 = t1.col1 
       and t2.col3 = t1.col3 
0

全部加入就可以了,我认为,你只需要选择不是所有的,但你想要的东西,像

SELECT ISNULL(table_1.col1, table_2.col1) col1, table_1.col2, table2.col2, ISNULL(table_1.col3, table_2.col3) col3 

ISNULL可能会因什么数据库系统上调用不同的u使用

0
SELECT col1 
,  t1.col2 
,  t2.col3 
,  col3 
FROM table1 t1 
FULL OUTER JOIN table2 t2 
USING (col1, col3)