如何在mysql中离开联接多个一对多表?

编程入门 行业动态 更新时间:2024-10-25 21:29:07
本文介绍了如何在mysql中离开联接多个一对多表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在mysql中联接三个表时遇到问题.

i have a problem with joining three tables in mysql.

让我们说有一个名为posts的表,我将其保留在其中,有一个名为likes的表,其中存储了user_id和post_id,还有第三个名为comments的表,其中存储了user_id和post_id,并在其中评论文本.

lets say we have a table named posts which I keep my entries in it, i have a table named likes which i store user_id's and post_id's in and a third table named comments which i store user_id's and post_id's and comment's text in it.

我需要一个查询来获取我的条目列表,其中包含每个条目的喜欢和评论数.

I need a query that fetches list of my entries, with number of likes and comments for each entry.

我正在使用此查询:

SELECT posts.id, count(comments.id) as total_comments, count(likes.id) as total_likes FROM `posts` LEFT OUTER JOIN comments ON comments.post_id = posts.id LEFT OUTER JOIN likes ON likes.post_id = posts.id GROUP BY posts.id

但是此查询存在问题,如果某项的评论为空,则喜欢"计数就可以了,但是如果某条目具有2条评论和4个赞",则total_comments和total_likes均为"8",这意味着mysql将它们相乘. 我很困惑,我不知道该怎么办.

but there is a problem with this query, if comments are empty for an item, likes count is just ok, but lets say if an entry has 2 comments and 4 likes, both total_comments and total_likes will be "8", meaning that mysql multiplies them. I'm confused and I dont know what whould I do.

谢谢你.

推荐答案

使用count(distinct comments.id)和count(distinct likes.id),前提是这些ID是唯一的.

Use count(distinct comments.id) and count(distinct likes.id), provided these ids are unique.

更多推荐

如何在mysql中离开联接多个一对多表?

本文发布于:2023-10-28 18:42:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1537451.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   如何在   mysql

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!