2012-09-21 47 views
0

我有以下3個表,其中B,C具有多對一關係船與A,並且我需要與MySQLMySQL的複製SUM,一對多關係船

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 

回答

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;