简体   繁体   English

用SQL比较两个表

[英]Comparing two tables with SQL

I need a query to produce a compare table between two tables. 我需要一个查询来产生两个表之间的比较表。

Something like this: 像这样:

table_1: 表格1:

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

table_2: 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    |      NULL      |        4       |   c_comment

Also, I need to keep the order, st if x in col1 is before y in col1 in any of the tables it will also be before it in the query result. 另外,我需要保持顺序,如果在任何一个表中col1中的x在col1中的y之前,它在查询结果中也将在它之前。 I tried to do it with FULL JOIN but it duplicates col1 and col3. 我试图用FULL JOIN来做到这一点,但是它复制了col1和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 根据您使用的数据库系统,可以将ISNULL称为不同

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM