gpt4 book ai didi

mysql - 连接多个表并使用 MySQL 的 Count

转载 作者:行者123 更新时间:2023-11-29 21:16:31 25 4
gpt4 key购买 nike

所以我让自己陷入了一片困惑。

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

  • 表 1 - 用户帖子
  • 表 2 - 用户
  • 表 3 - 点赞
  • 表 4 - 评论

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

如果帖子没有任何喜欢或评论,那么理想情况下我们应该显示零。

下面的查询将所有内容连接起来,但返回所有内容的多行,因为它也为每个评论或点赞返回 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
  • 用户 ID
  • 喜欢日期

app_comments

  • comment_id
  • comment_user_id
  • post_id
  • comment_body
  • 评论日期

app_posts

  • post_id
  • 用户 ID
  • 帖子内容
  • 发布日期
  • post_public

app_user

  • 用户 ID
  • 用户优先
  • 用户最后
  • 用户头像
  • user_banned

当前返回的示例如下(为了方便起见,进行了删减)

enter image description here

您会看到 post_id 重复多次。

我希望它返回一次 post_id,以及新列中的“喜欢”和“评论”计数(我不知道该怎么做)。

西蒙

最佳答案

您可能缺少 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 - 连接多个表并使用 MySQL 的 Count,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35893828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com