简体   繁体   中英

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

I have two tables that look like this:

Table 1:

name | event | country

Table 2:

name | event

There are no overlapping rows between Table 1 and Table 2, because of the 'event' column. I wanted to union Table 1 with Table 2 since there are no overlaps, but I also want to fill in 'country' for Table 2 using the values from Table 1, with 'name' as the Join key. How do I do this?

If the relation of the 2 tables is 1:1 you can use UNION ALL for table1 and a query that joins (with a left join just in case there are no matches) table2 to table1 to retrieve the value of the column country :

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

or with a correlated subquery:

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

Try this

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

This sounds like a full join:

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

If your database doesn't support full join , you can use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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