0

我有以下 3 个表,其中 B、C 与 A 具有多对一关系,我需要使用 MySql 生成以下结果表

   Table A           Table B              Table C
    id  name       id   A.id    qty        id   A.id
    1   a          1    1       5          1    1
    2   b          2    1       10         2    1
    3   c          3    2       4          3    2
                   4    3       6          4    2
                   5    2       7



 Expected Result Table

C.id    A.id    sum(B.qty Group by A.id)
1       1       15
2       1       15
3       2       11
4       2       11
4

1 回答 1

2
select c.id, a.id, sum(b.qty)
from c
inner join a on c.a_id = a.id
inner join b on b.a_id = a.id
group by c.id, a.id

或者在你的情况下,你只是不需要表 a

select c.id as cid, c.a_id as aid , sum(b.qty) as totalqty
from c
inner join b on b.a_id =c.a_id
group by c.id, c.a_id;
于 2012-09-21T10:31:41.963 回答