You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多表查询:如何基于ID列合并3张表得到指定结果?

如何合并三张表得到指定查询结果?

现有表结构及数据

表1(假设表名为a)

ID    Count A
-----------------
1           1
2           2

表2(假设表名为b)

ID    Count B
-----------------
1           3
3           4

表3(假设表名为c)

ID    Count C
-----------------
2           5
4           6

期望查询结果

ID    Count A    Count B    Count C
-----------------------------------
1           1          3 
2           2                     5
3                      4          
4                                 6

我尝试过的SQL语句

第一种:

select a.id, a.count_a, b.count_b, c.count_c
from a
full outer join b
    on a.id = b.id
full outer join c  
    on a.id = c.id
    or b.id = c.id 

第二种:

select id, count_a
from a
union
select id, count_b
from b
union
select id, count_c
from c  

但以上语句都无法得到期望结果,求正确解决方法。


正确解决方法

核心思路是先获取所有存在的ID集合,再基于这个集合分别左连接三张表,保证每个ID都被包含且对应列数值正确匹配。

方法一:兼容性更强的UNION+左连接方案

该方案适用于所有支持基本SQL语法的数据库(包括不支持全连接的MySQL):

select 
    all_ids.id,
    a.count_a,
    b.count_b,
    c.count_c
from 
    (select id from a
     union
     select id from b
     union
     select id from c) as all_ids
left join a on all_ids.id = a.id
left join b on all_ids.id = b.id
left join c on all_ids.id = c.id
order by all_ids.id;

方法二:全连接+COALESCE方案(适用于PostgreSQL、SQL Server等支持全连接的数据库)

通过逐步全连接并使用coalesce函数统一ID字段:

select
    coalesce(a.id, b.id, c.id) as id,
    a.count_a,
    b.count_b,
    c.count_c
from a
full outer join b on a.id = b.id
full outer join c on coalesce(a.id, b.id) = c.id
order by id;

内容的提问来源于stack exchange,提问作者zenzic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 18:50:00