繁体   English   中英

SQL - 联合两个表,但加入其中一列

[英]SQL — Union two tables but Join on one of the columns

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

表格1:

name | event | country

表 2:

name | event

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

如果 2 个表的关系是1:1 ,您可以对table1使用UNION ALL和一个将table2连接到table1的查询(使用左连接,以防没有匹配项)以检索列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

尝试这个

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

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

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

暂无
暂无

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

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