SQL使用`full outer join` 并列关联多个表

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 主键相同部分合并成同一行了。

结论:如果并列全关联,那么关键表与其他表如果关联主键相同的就会合并到同一行数据,如果不是关键表之间的关联,那么尽管主键相同,也会分散到不同行。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值