代码之家  ›  专栏  ›  技术社区  ›  good_afternoon

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

  •  0
  • good_afternoon  · 技术社区  · 6 年前

    此查询中的表如下所示:

    • 岗位
    • 用户
    • 职位类别

    我正在尝试查询有关某个帖子的所有相关信息,这些帖子有一些关系,比如发表帖子的用户、对该特定帖子的评论、帖子上的多个或无标签以及帖子所在的类别。

    以下是我的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 回复  |  直到 6 年前
        1
  •  1
  •   Amit    6 年前

    原因是使用多个 JOIN s的作用类似于笛卡尔积,因此得到2*3=6行。应用count时,得到6个有效(非null)值,这就是结果。

    要修复,请使用:

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