【问题标题】:Joining multiple Tables and using Count with MySQL连接多个表并在 MySQL 中使用 Count
【发布时间】:2016-03-09 14:06:24
【问题描述】:

所以我把自己搞得一团糟。

基本上,我有一个小型社交网络应用程序,我需要将 4 个不同的表合并到一个视图中。

  • 表 1 - 用户帖子
  • 表 2 - 用户
  • 表 3 - 喜欢
  • 表 4 - 评论

然后我需要返回一个帖子列表,其中包含用户详细信息,然后分别为每个帖子添加点赞数和 cmets 数列。

如果帖子没有任何点赞或 cmets,那么理想情况下我们应该显示零。

下面的查询将所有内容连接起来,但返回多行所有内容,因为它为每个评论或喜欢返回 1 行。

谁能帮我把这些结合起来?

SELECT *
FROM app_posts AS p
LEFT JOIN app_comments AS c ON c.post_id = p.post_id
LEFT JOIN app_user AS u ON u.user_id = p.user_id
LEFT JOIN app_likes AS l ON l.post_id = p.post_id
WHERE u.user_banned = 0
AND p.post_public = 1
ORDER BY p.post_date DESC

任何帮助将不胜感激!

表格列如下;

app_likes

  • like_id
  • post_id
  • user_id
  • liked_date

app_cmets

  • comment_id
  • comment_user_id
  • post_id
  • comment_body
  • comment_date

app_posts

  • post_id
  • user_id
  • post_content
  • post_date
  • post_public

app_user

  • user_id
  • user_first
  • user_last
  • 用户头像
  • user_banned

目前返回的一个例子如下(为了方便截断)

您会看到 post_id 重复了多次。

我希望它只返回一次 post_id,并在新列中包含“喜欢”和“cmets”的计数(我不知道该怎么做)。

西蒙

【问题讨论】:

  • 你目前的结果是什么,你想要的结果是什么?这将帮助我们找出问题所在。请阅读How-to-Ask 这里是START 了解如何提高问题质量并获得更好答案的好地方。
  • 我刚刚用我当前输出的 sn-p 编辑了我的问题。基本上,我需要返回每个 post_id 的 1 个实例,并将“likes”和“cmets”计数作为自动添加的新列。
  • @Simon 你忘了使用 'GROUP BY p.post_id'
  • @SimonHume 基本应该是GROUP BY,但看起来你有重复的数据、重复的评论和日期,所以你可能想看看你的查询

标签: mysql join left-join inner-join


【解决方案1】:

您可能缺少 GROUP BY...

SELECT p.*,u.*,count(distinct c.comment_id),count(distinct l.like_id)
FROM app_posts AS p
LEFT JOIN app_comments AS c ON c.post_id = p.post_id
LEFT JOIN app_user AS u ON u.user_id = p.user_id
LEFT JOIN app_likes AS l ON l.post_id = p.post_id
WHERE u.user_banned = 0
AND p.post_public = 1
GROUP BY p.post_id
ORDER BY p.post_date DESC

请注意,MySQL 允许您像这样草率地使用 GROUP BY,但是很多其他数据库 would require 您可以将“p.*”分解为显式 MAX(p.post_id),MAX(p.post_content), 等。

【讨论】:

  • 仅仅因为 MySQL 让你变得邋遢并不意味着你应该邋遢;)。
【解决方案2】:
SELECT p.post_id, COUNT(c.post_id) as num_comments, COUNT(l.like_id) as num_likes
FROM app_posts AS p
LEFT JOIN app_comments AS c ON c.post_id = p.post_id
LEFT JOIN app_user AS u ON u.user_id = p.user_id
LEFT JOIN app_likes AS l ON l.post_id = p.post_id
WHERE u.user_banned = 0
AND p.post_public = 1
GROUP BY  p.post_id
ORDER BY p.post_date DESC

【讨论】:

    【解决方案3】:

    尝试在查询末尾添加 Group by,如下所示

    SELECT *
    FROM app_posts AS p
    LEFT JOIN app_comments AS c ON c.post_id = p.post_id
    LEFT JOIN app_user AS u ON u.user_id = p.user_id
    LEFT JOIN app_likes AS l ON l.post_id = p.post_id
    WHERE u.user_banned = 0
    AND p.post_public = 1
    GROUP BY p.post_id
    ORDER BY p.post_date DESC
    

    【讨论】:

    • GROUP BY 没有聚合函数?
    猜你喜欢
    • 2016-02-01
    • 2017-09-07
    • 2016-06-06
    • 2023-03-18
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    • 2018-08-31
    • 2011-09-11
    相关资源
    最近更新 更多