答案 0 :(得分:2)
您基本上需要Full Outer Join
和Coalesce()
。以下查询应适用于主要的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 all
和group 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