如何在MySQL中将多个表连接到多个表?

问题描述:

我在连接mysql中的三个表时遇到了问题。如何在MySQL中将多个表连接到多个表?

,假设我们有一个表名为posts,我把我的项目中,我有一个表命名为likes我存储USER_ID的和POST_ID在和第三台名为comments我存储USER_ID的和POST_ID的和注释的文本在它。

我需要一个查询来获取我的条目列表,每个条目的喜欢数和评论数。使用

林这个查询:

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将它们相乘。 我很困惑,我不知道该怎么办。

感谢advace。

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

+0

谢谢,工作就像一个魅力。 – Sallar 2011-01-10 20:18:18

嗯,这是一个方式来处理它(假设MySQL允许派生表):

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

你也可以使用相关子查询。如果没有匹配的记录,您可能需要一个案例统计信息来计入0。

让我们尝试相关子查询:

SELECT posts.id, 
(select count(Id) from comments where post_id = posts.id) as total_comments, 
(select count(Id) from likes where post_id = posts.id) as total_likes 
FROM `posts` 
+0

谢谢,但是这个查询为第一条记录返回了12个喜欢和2条评论(它有4个喜欢和2条评论),并且对于其他所有行都为NULL。 – Sallar 2011-01-10 20:16:03