【问题标题】:SQL - Query count for related table affected by other joinSQL - 受其他联接影响的相关表的查询计数
【发布时间】:2018-09-02 17:32:22
【问题描述】:

本次查询中的表如下:

  • 发布
  • 用户
  • 评论
  • 标签
  • Tagged_Post
  • Post_Category

我正在尝试查询有关帖子的所有相关信息,这些信息具有发布帖子的用户、该特定帖子上的 cmets、帖子上的许多或没有标签以及帖子所在的类别等关系。

这是我的 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
        )

)

标签的数量似乎影响了 cmets 的计数。例如,在第一篇文章中,有 3 个 cmets 和 2 个标签。 ID 为 1 的帖子上的 cmets 计数显示为 6。如果我要在此帖子上添加一个额外的标签(总共 3 个标签),那么评论数将显示 9(3 个标签 x 3 cmets)。

谁能帮我理解为什么会这样?

【问题讨论】:

  • 您的查询无效。您只有GROUP BY post.id,但列表中有很多列,它们既不是post.id,也不是聚合函数的参数。尽管 MySQL 的旧版本或配置松散的版本(我假设是您的 DBMS?)接受这一点,但结果可能很有趣。
  • 我正在对所有帖子进行查询,无论是谁发布的。这就是为什么我认为按 ID 分组是可以接受的。你会怎么做?我也在选择 post.* 所以 ID 在那里

标签: mysql sql


【解决方案1】:

原因是使用多个JOINs 就像笛卡尔积一样,因此您将获得 2*3=6 行的组。应用计数时,您会得到 6 个有效(非空)值,这就是您的结果。

要修复,请使用:

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

【讨论】:

  • 我看到你编辑了你的答案。很好……计算不同的评论ID而不是计算post_id。我仍然觉得我的查询很糟糕,但我必须坚持下去。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-26
  • 1970-01-01
  • 2018-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多