首页 > 解决方案 > MYSQL 返回具有相关帖子计数的所有类别

问题描述

我正在尝试返回所有类别以及与它们相关的任何相关/标记帖子的计数。

这是表结构的示例。

帖子表

id      name    user_id
1       post 1  1
2       post 2  2
3       post 3  1

标签表

id      tag_name
1       Category 1
2       Category 2
3       Category 3

帖子 标签 枢轴

id      tag_id  post_id
1       3       2
2       3       2
3       1       3

这是查询的细分

获取所有标签

SELECT t.tag_name
FROM tags t
GROUP BY
    t.tag_name

这将返回我的所有标签

获取所有带有帖子计数的标签

SELECT t.tag_name, count(p.id) as count FROM products p
LEFT JOIN tags_pivot c ON p.id = c.post_id
LEFT JOIN tags t ON t.id = c.tag_id
WHERE p.user_id = 1
GROUP BY
    t.tag_name

这仅在找到结果/帖子的位置返回标签。即使计数为 0,我也想返回所有标签,并且该特定标签的计数显示为 0。有没有办法像这样构造查询?我曾尝试使用左外连接,但我仍然得到相同的结果。

标签: mysql

解决方案


由于您想要考虑所有标签,因此您的基表应该是tags表,并且您LEFT JOIN应该从那里开始。LEFT JOIN总是考虑最左表中的所有数据,并且只连接右表中与连接条件匹配的数据。所以所有的tags都被考虑(因为它是最左边的表),但是只有那些posts数据透视表中的被考虑。尝试以下操作:

SELECT t.tag_name, COUNT(p.id) as count 
FROM tags AS t 
LEFT JOIN tags_pivot AS c ON t.id = c.tag_id 
LEFT JOIN posts AS p ON p.id = c.post_id 
GROUP BY
    t.tag_name

编辑根据 OP 的评论,只有那些帖子要考虑 where user_id = 1。为了实现这一点,我们在表中添加了一个额外的AND要求。这是更新的查询:LEFT JOINposts

SELECT t.tag_name, COUNT(p.id) as count 
FROM tags AS t 
LEFT JOIN tags_pivot AS c ON t.id = c.tag_id 
LEFT JOIN posts AS p ON p.id = c.post_id AND p.user_id = 1
GROUP BY
    t.tag_name

推荐阅读