多表查询:如何基于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
相关产品推荐
相关产品推荐

