mysql - 使用 parent_id 求和并分组

标签 mysql sql ruby-on-rails ruby ruby-on-rails-4

我有表:

类别

+----+-----------+---------------+
| 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/

相关文章:

sql - 如何在 SQL 中以这种特定方式合并列

MySql 按顺序选择岛屿并删除间隙

ruby-on-rails - 如何在Rails View 中注释代码?

mysql - 使用 AngularJS 和 Spring Security 进行身份验证

php - 使用 jquery/ajax 插入 MYSQL DB 500 内部服务器错误

SQL如何控制分组列

ruby-on-rails - 将 with_options 与 Rails 表单助手一起使用

ruby-on-rails - Rails - 更新模型 "in the future"

mysql - 如何更改表的默认排序规则?

mysql - 如何导出 Mysql 表的数据,包括另一个表的引用 ID 的值