SQL-在SQL中组合两个表
我有一个如下表,其中仅包含2011年和2012年的数据:SQL-在SQL中组合两个表,sql,oracle,join,Sql,Oracle,Join,我有一个如下表,其中仅包含2011年和2012年的数据: country year value1 ABCD 2011 x1 ABCD 2012 x2 PQRS 2011 x3 PQRS 2012 x4 另一张表为2010年至2014年的数据,如下所示: country year value2 ABCD 2010 y1 ABCD 2011
country year value1
ABCD 2011 x1
ABCD 2012 x2
PQRS 2011 x3
PQRS 2012 x4
另一张表为2010年至2014年的数据,如下所示:
country year value2
ABCD 2010 y1
ABCD 2011 y2
ABCD 2012 y3
ABCD 2013 y4
ABCD 2014 y5
PQRS 2010 y6
PQRS 2011 y7
PQRS 2012 y8
PQRS 2013 y9
PQRS 2014 y10
我想要一个组合表,如下所示:
country year value2 value1
ABCD 2010 y1 null
ABCD 2011 y2 x1
ABCD 2012 y3 x2
ABCD 2013 y4 null
ABCD 2014 y5 null
PQRS 2010 y6 null
PQRS 2011 y7 x3
PQRS 2012 y8 x4
PQRS 2013 y9 null
PQRS 2014 y10 null
有人能建议一条路吗?I这两种情况的主键是(国家+年份)。
此外,如果有许多这样的表,那么解决方案是什么
谢谢。使用
左键加入
:
select t2.*, t1.value1
from table2 t2 left join
table1 t1
on t2.country = t1.country and t2.year = t1.year;
如果第二个表没有重复第一个表中的行,则需要一个
完全外部联接
(或某种联合
)。但是,考虑到问题中的数据,左连接
就足够了(应该有更好的性能)。使用左连接
:
select t2.*, t1.value1
from table2 t2 left join
table1 t1
on t2.country = t1.country and t2.year = t1.year;
如果第二个表没有重复第一个表中的行,则需要一个
完全外部联接
(或某种联合
)。但是,考虑到问题中的数据,左连接就足够了(应该有更好的性能)。看起来您需要一个完整的外部连接:
select country, year, t1.value1, t2.value2
from table_1 t1
full outer join table_2 t2 using (country, year);
看起来您需要一个完整的外部联接:
select country, year, t1.value1, t2.value2
from table_1 t1
full outer join table_2 t2 using (country, year);
您正在寻找的是一个完全外部连接
:
SELECT COALESCE(t1.country, t2.country) AS country,
COALESCE(t1.year, t2.year) AS year
t1.value1, t2.value2
FROM table1 AS t1
FULL OUTER JOIN table2 AS t2
ON t1.country = t2.country AND t1.year = t2.year
您正在寻找的是一个完全外部连接
:
SELECT COALESCE(t1.country, t2.country) AS country,
COALESCE(t1.year, t2.year) AS year
t1.value1, t2.value2
FROM table1 AS t1
FULL OUTER JOIN table2 AS t2
ON t1.country = t2.country AND t1.year = t2.year
Oracle 11g数据库Oracle 11g数据库工作正常!!如果有很多表,我想把它们合并在一个表中,你能告诉我解决方案吗way@ShubhamGoyal . . . 假设您有一个包含所有行的主表,那么您只需为每个表添加left join
s即可。工作非常出色!!如果有很多表,我想把它们合并在一个表中,你能告诉我解决方案吗way@ShubhamGoyal . . . 假设您有一个包含所有行的主表,那么您只需为每个表添加left join
s即可。谢谢!!它工作得很好。你能告诉我有多个表的解决方案吗?我想以相同的方式组合它们。只需为附加表添加类似的join
条件谢谢!!它工作得很好。你能告诉我有多个表的解决方案吗?我想用同样的方式组合它们。只需为其他表添加类似的join
条件即可