gpt4 book ai didi

mysql - 使用 parent_id 求和并分组

转载 作者:行者123 更新时间:2023-11-30 22:23:58 25 4
gpt4 key购买 nike

我有表:

类别

+----+-----------+---------------+
| id | parent_id | name |
+----+-----------+---------------+
| 1 | NULL | Dong ho nam |
| 2 | 1 | dong ho nam 1 |
| 3 | 1 | dong ho nam 2 |
| 4 | 1 | dong ho nam 3 |
| 5 | 1 | dong ho nam 4 |
| 6 | NULL | Dong ho nu |
| 7 | 6 | Dong ho nu 1 |
| 8 | 6 | Dong ho nu 2 |
| 9 | 6 | Dong ho nu 3 |
+----+-----------+---------------+

和表产品:

+----+-------------+---------------+
| id | category_id | quantity |
+----+-------------+---------------+
| 1 | 6 | 10 |
| 2 | 3 | 2 |
| 3 | 3 | 4 |
| 4 | 2 | 12 |
| 5 | 4 | 6 |
| 6 | 2 | 0 |
| 7 | 6 | 8 |
| 8 | 8 | 22 |
| 9 | 9 | 4 |
+----+-------------+---------------+

我要选择类别,sum(quantity)
//(所有数量的产品都属于category且category.parent_id = null)

结果:

+----+-----------+---------------+-----------+
| id | parent_id | name | quantity |
+----+-----------+---------------+-----------+
| 1 | NULL | Dong ho nam | 24 |
| 6 | NULL | Dong ho nu | 44 |
+----+-----------+---------------+-----------+

如何使用sql查询(或rails)可以达到以上结果。 谢谢。

最佳答案

您需要同时聚合父项和子项。像这样的东西应该很接近:

select c.id, p.quantity + coalesce(sum(p2.quantity),0) 
from categories c
join (
select category_id, sum(quantity) quantity
from products
group by category_id) p on c.id = p.category_id
left join categories c2 on c.id = c2.parent_id
left join products p2 on c2.id = p2.category_id
where c.parent_id is null
group by c.id

关于mysql - 使用 parent_id 求和并分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35858836/

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