用SQL比较两个表

时间:2011-02-16 16:19:55

标签: 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中位于y之前,它也将位于查询结果中。 我尝试用FULL JOIN做它,但它复制了col1和col3。

谢谢!

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我认为完全加入是好的,你只需选择不是全部,而只是选择你想要的,比如

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

根据您使用的数据库系统

,可能会调用ISNULL

答案 2 :(得分:0)

SELECT col1
,      t1.col2
,      t2.col3
,      col3
FROM   table1 t1
FULL OUTER JOIN table2 t2
USING (col1, col3)
相关问题