首页 > 解决方案 > SQL - 联合两个表,但在其中一列上加入

问题描述

我有两个看起来像这样的表:

表格1:

name | event | country

表 2:

name | event

由于“事件”列,表 1 和表 2 之间没有重叠行。由于没有重叠,我想将表 1 与表 2 合并,但我还想使用表 1 中的值填写表 2 的“国家”,并将“名称”作为连接键。我该怎么做呢?

标签: sqljoinunion

解决方案


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

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);

推荐阅读