从具有相同主键但值不同的两个表中选择一个表?

时间:2016-11-24 06:58:52

标签: mysql

Table1           Table2

id  | name       id   | name
-----------      ------------
2   | A           2   |  E   
4   | B           3   |  F
6   | C           4   |  G
8   | D           5   |  H    

输出:

Id  |  name
------------
2   |  A *** E
4   |  B *** G
6   |  C *** EMPTY
8   |  D *** EMPTY
3   |  EMPTY *** F
5   |  EMPTY *** H

2 个答案:

答案 0 :(得分:1)

您没有指定DBMS,因此这是ANSI SQL:

select coalesce(t1.id, t2.id) as id,
       t1.name, 
       t2.name
from table1 t1
  full outer join table2 t2 on t1.id = t2.id
where t1.name is distinct from t2.name;

答案 1 :(得分:0)

select isnull(a.id, b.id), case when a.value is not null and b.value is not null then a.value + '***' + b.value

否则合并(a.value,b.value)从table_1结束a.id = b.id

上的完整外连接table_2 b