Mysql - 按多个表和列分组

时间:2013-05-29 16:03:26

标签: mysql sql group-by

我有以下两个表格:

 content:
 ========
 cid | iid | qty
 ---------------
   1 |   7 | 42
   2 |   7 |  1
   3 |   8 | 21

 ret:
 ====
 rid | cid | qty
 --------------
   1 |   1 |   2
   2 |   1 |  10
   3 |   2 |   1

我想为每个iid检索content.qtyret.qty的总和 例如,对于给定的表,结果将是:

iid=7, SUM(content.qty) = 43, SUM(ret.qty)=13

iid=8, SUM(content.qty) = 21, SUM(ret.qty)=0

有没有办法在一个查询中执行此操作?

提前,谢谢!

1 个答案:

答案 0 :(得分:0)

这有点复杂,因为你不需要在你的总和中重复。要解决该问题,请将聚合作为子查询单独进行。第一个直接在content,第二个从content加入ret以获取iid列。

以下查询遵循此方法,并假设cidcontent上的唯一键:

select c.iid, c.qty + coalesce(r.qty, 0)
from (select c.iid, SUM(qty) as cqty
      from content c 
      group by c.iid
     ) c left outer join
     (select c.iid, SUM(r.qty) as rqty
      from ret r join
           content c
           on r.cid = c.cid
      group by c.iid
     ) r
     on c.iid = r.iid;
相关问题