从2个不相关的表中选择并合并唯一的ID列

时间:2015-03-26 12:08:12

标签: mysql

我试图返回来自2个表的数据的组合结果,但是需要合并两个ID列以形成一个结果集,完全外部联接是最接近我必须返回正确的行号

示例:

T1

ID  A
a   s
b   s
e   s
f   s

T2

ID  B
a   a
c   a
d   a
f   a

结果

ID   A      B
a    s      a
b    s      NULL
c    NULL   a
d    NULL   a
e    s      NULL
f    s      a



    declare @t1 table (
                  ID varchar(1),
                  A varchar(1)
                 )
insert into @t1 values ('a','s')
insert into @t1 values ('b','s')
insert into @t1 values ('e','s')
insert into @t1 values ('f','s')

declare @t2 table (
                  ID varchar(1),
                  B varchar(1)
                 )

insert into @t2 values ('a','a')
insert into @t2 values ('c','a')
insert into @t2 values ('d','a')
insert into @t2 values ('f','a')

select * from @t1
select * from @t2

1 个答案:

答案 0 :(得分:0)

如果您使用的是MySQL;你在MySQL中没有完全加入,但你肯定可以emulate them

对于从this SO question转录的代码SAMPLE,您有:

有两个表t1,t2:

SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id

所以你的查询变为:

SELECT COALESCE(t1.ID, t2.ID) As ID, t1.A As A, t2.B As B FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id
UNION
SELECT COALESCE(t1.ID, t2.ID) As ID, t1.A As A, t2.B As B FROM table1 t1
RIGHT JOIN table2 t2 ON t1.id = t2.id
order by ID

它为您提供了正确的结果,输入为:

ID   A      B
a    s      a
b    s      NULL
c    NULL   a
d    NULL   a
e    s      NULL
f    s      a