开发者

Comparing two tables with SQL

I need a query to produce a compare table between two tables.

Something like this:

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

Query result:

col1  |  table_1.col2  |  table_2.col2  |  col3
 a    |       1        |        3       |   a_comment
 b    |       2        |       NULL     |   b_comment
 c    |  开发者_JAVA百科    NULL      |        4       |   c_comment

Also, I need to keep the order, s.t. if x in col1 is before y in col1 in any of the tables it will also be before it in the query result. I tried to do it with FULL JOIN but it duplicates col1 and col3.

Thank you!


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


Full join is ok i think, you just have to select not all but just what you want, like

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

ISNULL might be called different depending on what database system u use


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜