计算子类别中的数字

时间:2015-04-16 09:24:43

标签: php mysql

有两张桌子。

mdl_course_categories:
+----+---------------+----------+
| id | name          |  parent  |
+----+---------------+----------+
| 1  | Some category |  0       |
| 2  | Some category |  1       |
...

mdl_course:
+----+--------------+-------------+
| id | category     | name        |
+----+--------------+-------------+
| 1  | 1            | Course name |
...

mdl_course.categorymdl_course_categories.id相关。

因此,如果我们有一个类别包含1门课程,并且在此类别子类别中包含2门课程,则类别必须包含3门课程,依此类推。 E.g:

category1 (2 courses there)
 - subcategory1 (8 courses there)
    - subsubcategory (1 course there)
 - subcategory2 (4 courses there)

需要输出:

category1 (15=2+8+1+4)
 - subcategory1 (9=8+1)
    - subsubcategory (1)
 - subcategory2 (4)

这是我的MySQL代码:

SELECT category.name AS name,

COUNT(mdl_course.category) + (

    SELECT COUNT(mdl_course.category) FROM mdl_course_categories AS subcategory
    LEFT JOIN mdl_course ON mdl_course.category = subcategory.id
    WHERE category.id = subcategory.parent
) AS count

FROM mdl_course_categories AS category
LEFT JOIN mdl_course ON mdl_course.category = category.id
GROUP BY category.id ORDER BY name ASC

但它只计算一个子级别,而不是递归。 你能帮助更多的通用代码,也许php + mysql? 目标是将每个课程数量的类别列为课程总和 在所有子类别中。

0 个答案:

没有答案