如何通过gid,uid将多个表合并到sql组中的一个表中?

时间:2018-11-01 13:20:54

标签: sql

这是项目中遇到的问题。请看我的图片描述。

我需要将多个表聚合到一个表中。 uid和gid是固定的,其他xxx_count不同。

可以使用mysql或oracle sql来做。

enter image description here

3 个答案:

答案 0 :(得分:2)

您基本上需要Full Outer JoinCoalesce()。以下查询应适用于主要的RDBMS(MySQL除外):

SELECT 
  a.uid,
  a.gid, 
  COALESCE(a.file_count, 0) AS file_count, 
  COALESCE(b.reply_count, 0) AS reply_count, 
  COALESCE(c.ask_count, 0) AS ask_count 
FROM 
 a 
FULL OUTER JOIN b ON a.uid = b.uid AND a.gid = b.gid 
FULL OUTER JOIN c ON a.uid = c.uid AND a.gid = c.gid 

答案 1 :(得分:1)

您可以使用union allgroup by

select uid, gid, sum(file_count), sum(reply_count), sum(ask_count)
from ((select uid, gid, file_count, 0 as reply_count, 0 as ask_count from a
      ) union all
      (select uid, gid, 0 as file_count, reply_count, 0 as ask_count from b
      ) union all
      (select uid, gid, 0 as file_count, 0 as reply_count, ask_count from c
      )
     ) abc
group by uid, gid;

如果发现有多个表,则此方法比full join更简单-必须处理NULL创建的所有full join值很麻烦。

答案 2 :(得分:0)

使用Oracle的nvl函数,也许对您有帮助:

select a.uid, a.gid, nvl(a.file_count,0) , nvl(b.reply_count, 0), nvl(c.ask_count,0)
from a
left join b on a.uid = b.uid and a.gid = b.gid
left join c on a.uid = c.uid and a.gid = c.gid