联合两个表,但在其中一列上连接

g52tjvyc  于 2021-08-01  发布在  Java
关注(0)|答案(3)|浏览(265)

我有两张这样的table:
表1:

name | event | country

表2:

name | event

由于“event”列的原因,表1和表2之间没有重叠行。我想将表1与表2合并,因为不存在重叠,但我还想使用表1中的值为表2填写'country','name'作为联接键。我该怎么做?

rbpvctlc

rbpvctlc1#

如果两个表的关系是 1:1 你可以用 UNION ALL 为了 table1 以及连接的查询(如果没有匹配项,则使用左连接) table2table1 检索列的值 country :

select t1.* from table1 t1
union all
select t2.*, t1.country 
from table2 t2 left join table1 t1
on t1.name = t2.name

或使用相关子查询:

select t1.* from table1 t1
union all
select t2.*, (select t1.country from table1 t1 where t1.name = t2.name)
from table2 t2
bejyjqdl

bejyjqdl2#

试试这个

SELECT * FROM TABLE1 t1
   UNION
   Select t2.*, t1.country from table2 t2 
   Join table1 t1 on t2.name=t1.name
pw9qyyiw

pw9qyyiw3#

这听起来像是一个完全连接:

select *
from table1 t1 full join
     table2 t2
     using (name, event);

如果你的数据库不支持 full join ,您可以使用:

select t1.name, t1.event, t1.country
from table1 t1
union all
select t2.name, t2.event, null
from table2 t2
where not exists (select 1 from table1 t1 where t1.name = t2.name and t1.event = t2.event);

相关问题