左连接时MySQL错误的计数值

时间:2014-09-12 14:24:53

标签: mysql join

我不确定我在这里做错了什么。

这可以产生预期的效果 (在评级表中获取食谱列表和评级总数)

SELECT recipes.RecipeID, 
       recipes.Name, 
       recipes.RatingTotal, 
       recipes.ImageBig, 
       users.Email, 
       users.FullName, 
       users.UserImageBig, 
       COUNT(ratings.RecipeID) AS trates 
FROM   recipes 
       LEFT JOIN users 
              ON recipes.User = users.Email 
       LEFT JOIN ratings 
              ON ratings.RecipeID = recipes.RecipeID 
GROUP  BY RecipeID 
ORDER  BY RecipeID DESC 
LIMIT  3 

这不起作用 (获取配方列表以及评级表中的评级总数以及评论总数。查询运行但计数列中的值是错误的)

SELECT recipes.RecipeID, 
       recipes.Name, 
       recipes.RatingTotal, 
       recipes.ImageBig, 
       users.Email, 
       users.FullName, 
       users.UserImageBig, 
       COUNT(ratings.RecipeID)        AS trates, 
       COUNT(recipecomments.RecipeID) AS crate 
FROM   recipes 
       LEFT JOIN users 
              ON recipes.User = users.Email 
       LEFT JOIN ratings 
              ON ratings.RecipeID = recipes.RecipeID 
       LEFT JOIN recipecomments 
              ON recipecomments.RecipeID = recipes.RecipeID 
GROUP  BY RecipeID 
ORDER  BY RecipeID DESC 
LIMIT  3 

如果有2条评论,则返回实际数字的4倍。评级也将变为4。

1 个答案:

答案 0 :(得分:2)

在第二个查询中,您添加了另一个与recipecomments的左连接,这肯定会有多对一的关系,因此RecipeID会有重复的行,并且计数会超出您的预期结果,因此您的问题就会出现问题您需要在计数函数中使用distinct来仅计算唯一的实例,同时crate计算recipecomments

的ID
SELECT recipes.RecipeID, 
       recipes.Name, 
       recipes.RatingTotal, 
       recipes.ImageBig, 
       users.Email, 
       users.FullName, 
       users.UserImageBig, 
       COUNT(DISTINCT ratings.RecipeID)        AS trates, 
       COUNT(DISTINCT recipecomments.ID) AS crate 
FROM   recipes 
       LEFT JOIN users 
              ON recipes.User = users.Email 
       LEFT JOIN ratings 
              ON ratings.RecipeID = recipes.RecipeID 
       LEFT JOIN recipecomments 
              ON recipecomments.RecipeID = recipes.RecipeID 
GROUP  BY RecipeID 
ORDER  BY RecipeID DESC 
LIMIT  3