gpt4 book ai didi

MySql重复SUM,一对多关系

转载 作者:行者123 更新时间:2023-11-29 08:45:58 26 4
gpt4 key购买 nike

我有以下 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

最佳答案

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;

关于MySql重复SUM,一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12528811/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com