此查询中的表如下所示:
我正在尝试查询有关某个帖子的所有相关信息,这些帖子有一些关系,比如发表帖子的用户、对该特定帖子的评论、帖子上的多个或无标签以及帖子所在的类别。
以下是我的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个评论)。
有人能帮我理解为什么会这样吗?