类别帖子数
我正在使用 Codeigniter 和 MySQL 构建一个博客。我的问题是,我有一张包含帖子的表格和一张包含类别的表格。我还有一个与 post_categories 的交叉引用表。我想做的是获取所有类别及其名称以及其名称下的帖子数量。
示例输出为:Hello World(1) Test(0) 等。
我很难找到一个 SQL 查询,该查询将连接三个表并获取计数,而且我也很难包装我的思考如何进行该查询。
这是我的表架构:
blgpost
====
id
*Other schema unimportant
blgpostcategories
=================
postid
categoryid
blgcategories
==========
id
name
*Other schema unimportant
I am building a blog with Codeigniter and MySQL. The question I have is this, I have a table with posts and one with categories. I also have a cross reference table with post_categories. What I am trying to do is get all the categories with their names and the number of posts they have under their name.
Example output would be: Hello World(1) Test(0) etc.
What I am having a hard time finding is a SQL query that will join the three tables and get me the counts, and I am also having a hard time wrapping my head around how to make that query.
Here is my table schema:
blgpost
====
id
*Other schema unimportant
blgpostcategories
=================
postid
categoryid
blgcategories
==========
id
name
*Other schema unimportant
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这应该会给你你想要的输出......
This should give you the output you want....
您不需要连接这三个表 -
blgpost
表中没有您需要的任何信息。You don't need to join the three tables - the
blgpost
table doesn't have any information in it that you need.对于空类别(没有链接到帖子的类别),使用
LEFT JOIN
将显示0
,而不是忽略它们。Using
LEFT JOIN
will show0
for empty categories (those without posts linked to them) rather than omitting them.