mysql - 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。有没有办法像这样构造查询?我曾尝试使用左外连接,但我仍然得到相同的结果。
解决方案
由于您想要考虑所有标签,因此您的基表应该是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 JOIN
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 AND p.user_id = 1
GROUP BY
t.tag_name
推荐阅读
- c# - Try Catch 中的返回值与泛型
- python-3.x - 将现有 Python3 方法转换为使用多处理
- security - 谷歌将我的密码保存到我使用 gmail 注册的其他网站是否正常?
- group-by - ABAP 字符串模板 - 带有 GROUP BY 的嵌入式表达式
- axon - 轴突事件处理超时
- c# - 如何使用 linq 从具有最新 dateTime 的集合中获取整个记录?
- android - Android Flutter 中的麦克风定时器
- amazon-web-services - 我想是否有办法使用 aws acm list-certificates 以及有效性和域名来查找所有 ACM 证书
- json - 如何在使用 Elasticsearch Nest 客户端和 Utf8Json 序列化程序时捕获与任何 POCO 属性不匹配的剩余 JSON 数据
- sql - SQL 查询的问题。选择具有 max() 列的行