简体   繁体   English

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

[英]Select from 2 unrelated tables and merge unique ID columns

I'm trying to return a combined result of data from 2 tables, but need to merge the ID column from both to form one result set, the full outer join is the closest I have to returning the correct row number. 我正在尝试从2个表返回数据的组合结果,但是需要合并两个表的ID列以形成一个结果集,完全外部联接是我必须返回正确行号的最接近的联接。

Example: 例:

T1 T1

ID  A
a   s
b   s
e   s
f   s

T2 T2

ID  B
a   a
c   a
d   a
f   a

Result 结果

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

If you are using MySQL; 如果您使用的是MySQL; you don't have FULL JOINS in MySQL, but you can surely emulate them . 您在MySQL中没有FULL JOINS,但是您可以肯定地模拟它们

For a code SAMPLE transcribed from this SO question you have: 对于从该SO问题记录下来的代码SAMPLE,您可以:

with two tables t1, t2: 有两个表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

So your query becomes: 因此,您的查询变为:

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

It gives me correct result with your inputs as: 您输入的内容为我提供了正确的结果:

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

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

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