此查询中的表如下:
- 发帖
- 用户
- 评论
- 标签
- Tagged_Post
- Post_Category
我正在尝试查询有关帖子的所有相关信息,这些信息具有诸如发布帖子的用户、对该特定帖子的评论、帖子上的多个标签或没有标签以及帖子所属的类别等关系。
这是我的 SQL 查询:
$sql = "SELECT post.*, user.name, user.avatar, group_concat(DISTINCT tag.slug) as tags, post_category.slug as category, count(comment.post_id) as comments
FROM post
INNER JOIN user on user.id = post.user_id
INNER JOIN post_category on post_category.id = post.category_id
LEFT JOIN tagged_post on tagged_post.post_id = post.id
LEFT JOIN tag on tagged_post.tag_id = tag.id
LEFT OUTER JOIN comment on post.id = comment.post_id
GROUP BY post.id";
输出如下:
Array
(
[0] => Array
(
[id] => 1
[user_id] => 1
[category_id] => 1
[title] => Hi, I'm Bob Ross. AMA
[body] => That's right. I'm bob ross and this is my post. I'm not dead btw
[date_created] => 2018-09-02 11:45:29
[date_modified] =>
[name] => bob_ross
[avatar] =>
[tags] => painting,ama
[category] => news-and-politics
[comments] => 6
)
[1] => Array
(
[id] => 2
[user_id] => 2
[category_id] => 2
[title] => I'm Saul Goodman!!
[body] => woohoo
[date_created] => 2018-09-02 12:12:12
[date_modified] =>
[name] => saul_goodman
[avatar] =>
[tags] =>
[category] => general-discussion
[comments] => 0
)
[2] => Array
(
[id] => 3
[user_id] => 3
[category_id] => 4
[title] => yo im jesse
[body] => test
[date_created] => 2018-09-02 12:24:45
[date_modified] =>
[name] => jesse_pinkman
[avatar] =>
[tags] => ama,painting
[category] => animals-and-nature
[comments] => 4
)
)
标签的数量似乎影响了评论的数量。例如,第一篇文章有 3 条评论和 2 个标签。 ID 为 1 的帖子的评论计数显示为 6。如果我要在此帖子上添加附加标签(总共 3 个标签),那么评论计数将显示 9(3 个标签 x 3 个评论)。
有人可以帮助我理解为什么会发生这种情况吗?
最佳答案
原因是使用多个 JOIN
的行为类似于笛卡尔积,因此您会获得该组的 2*3=6 行。当您应用计数时,您会得到 6 个有效(非空)值,这就是您的结果。
要修复,请使用:
... COUNT(DISTINCT comment.comment_id) as comments
关于mysql - SQL - 受其他连接影响的相关表的查询计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52139458/