SQL-受其他联接影响的相关表的查询计数

时间:2018-09-02 17:32:22

标签: mysql sql

此查询中的表如下:

  • 发布
  • 用户
  • 评论
  • 标签
  • 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条评论)。

有人可以帮助我了解为什么会这样吗?

1 个答案:

答案 0 :(得分:1)

原因是,使用多个JOIN就像笛卡尔积,因此该组将获得2 * 3 = 6行。当您应用count时,您将获得6个有效(非null)值,这就是您的结果。

要修复,请使用:

... COUNT(DISTINCT comment.comment_id) as comments