full outer join
一般在 SQL 中用于关联两个表取两个表的并集,百度搜索出来的都是用三个表嵌套取并集,尝试如果关联三个表平行关联会发生什么。
三个表如下,代码用presto
运行
以
表a
为主体
WITH a(e, f, g, h) as (
VALUES
(1, 2, 3, 0),
(1, 2, 4, 1)
),
b(e,f,g,i) as (
VALUES
(1, 2, 5, 2),
(2, 4, 5, 3)
),
c(e,f,g,j) as (
VALUES
(1, 2, 5, 6),
(3, 1, 2, 5)
)
select coalesce(a.e,b.e,c.e) as e, coalesce(a.f,b.f,c.f) as f, coalesce(a.g,b.g,c.g) as g, h, i, j
from a full outer join b on a.e=b.e and a.f=b.f and a.g=b.g
full outer join c on a.e=c.e and a.f=c.f and a.g=c.g ;
可以看到表b
和表c
主键相同部分没有合并成同一行
以
表b
为主体
WITH a(e, f, g, h) as (
VALUES
(1, 2, 3, 0),
(1, 2, 4, 1)
),
b(e,f,g,i) as (
VALUES
(1, 2, 5, 2),
(2, 4, 5, 3)
),
c(e,f,g,j) as (
VALUES
(1, 2, 5, 6),
(3, 1, 2, 5)
)
select coalesce(a.e,b.e,c.e) as e, coalesce(a.f,b.f,c.f) as f, coalesce(a.g,b.g,c.g) as g, h, i, j
from a full outer join b on a.e=b.e and a.f=b.f and a.g=b.g
full outer join c on b.e=c.e and b.f=c.f and b.g=c.g ;
可以看到表b
和表c
主键相同部分合并成同一行了。
结论:如果并列全关联,那么关键表与其他表如果关联主键相同的就会合并到同一行数据,如果不是关键表之间的关联,那么尽管主键相同,也会分散到不同行。