类别帖子数

发布于 2024-11-02 02:09:32 字数 424 浏览 1 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

花开雨落又逢春i 2024-11-09 02:09:32

这应该会给你你想要的输出......

SELECT c.name, COUNT(p.id) FROM
blgcategories c 
INNER JOIN blgpostcategories pc ON c.id = pc.categoryid
INNER JOIN blgpost p ON pc.postid = p.id
GROUP BY c.id

This should give you the output you want....

SELECT c.name, COUNT(p.id) FROM
blgcategories c 
INNER JOIN blgpostcategories pc ON c.id = pc.categoryid
INNER JOIN blgpost p ON pc.postid = p.id
GROUP BY c.id
辞别 2024-11-09 02:09:32

您不需要连接这三个表 - blgpost 表中没有您需要的任何信息。

SELECT COUNT(*), blgcategories.name 
FROM blgcategories INNER JOIN blgpostcategories 
ON blgcategories.id=blgpostcategories.categoryid 
GROUP BY blgcategories.id;

You don't need to join the three tables - the blgpost table doesn't have any information in it that you need.

SELECT COUNT(*), blgcategories.name 
FROM blgcategories INNER JOIN blgpostcategories 
ON blgcategories.id=blgpostcategories.categoryid 
GROUP BY blgcategories.id;
浪推晚风 2024-11-09 02:09:32
SELECT  name, COUNT(pc.id)
FROM    blgcategories c
LEFT JOIN
        blgpostcategories pc
ON      pc.categoryid = c.id
GROUP BY
        c.id

对于空类别(没有链接到帖子的类别),使用 LEFT JOIN 将显示 0,而不是忽略它们。

SELECT  name, COUNT(pc.id)
FROM    blgcategories c
LEFT JOIN
        blgpostcategories pc
ON      pc.categoryid = c.id
GROUP BY
        c.id

Using LEFT JOIN will show 0 for empty categories (those without posts linked to them) rather than omitting them.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文