计算属于某个类别及其子类别的所有帖子
我真的很感谢一些帮助解决我的问题:
我有 2 个 MySQL 表、类别和帖子,布局(简化)如下:
类别:
CATID - name -parent_id
帖子 :
PID - 名称 - 类别
我想要做的是获取每个类别的帖子总数,包括子类别中的所有帖子。
现在,我通过执行以下操作来获取每个(顶级)类别(但不是子类别)中的帖子总数:
"SELECT c.*, COUNT(p.PID) as postCount
FROM categories AS c LEFT JOIN posts AS p
ON (c.CATID = p.category)
WHERE c.parent='0' GROUP BY c.CATID ORDER BY c.name ASC";
问题再次是,如何获得每个类别的总和,包括每个类别的总数相关子类别?
将数据库重组为嵌套集格式是不可能的,因为我正在维护现有系统。
感谢您的帮助!
I would really appreciate some help with my problem:
I have 2 MySQL tables, categories and posts, laid out (simplified) like so:
categories:
CATID - name - parent_id
posts:
PID - name - category
What I would like to do is get the total amount of posts for each category, including any posts in subcategories.
Right now I am getting the total number of posts in each (top-level) category (but not subcategories) by doing:
"SELECT c.*, COUNT(p.PID) as postCount
FROM categories AS c LEFT JOIN posts AS p
ON (c.CATID = p.category)
WHERE c.parent='0' GROUP BY c.CATID ORDER BY c.name ASC";
The question once again is, how can I get the sum totals for each category including the totals for each related subcategory?
Restructuring the database to a nested set format is not possible, as I am maintaining an existing system.
Thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果类别不是无限嵌套的,您可以一次 JOIN 一层。以下是最多 3 层嵌套的示例:
If the categories are not nested infinitely, you can JOIN them one level at a time. Here's an example for up to 3 levels of nesting:
我想你想看看 Rollup 运算符。我相信这会让你得到你想要的。
http://msdn.microsoft.com/en-us /library/ms189305(SQL.90).aspx
兰迪
I think you want to look at the Rollup operator. I believe this will get you what you want.
http://msdn.microsoft.com/en-us/library/ms189305(SQL.90).aspx
Randy