正确使用计数

时间:2013-04-17 16:11:27

标签: mysql

我只想计算所有子评论,并计算属于图库的所有图片中的所有图片。

SELECT Count(Message.id) AS subCount, 
       Count(likes.id), 
       Image.id, 
       Image.date_created, 
       Image.likes, 
       Image.path 
FROM   images AS Image 
       LEFT JOIN messages AS Message 
              ON ( Message.object_id = Image.id 
                   AND Message.msg_type = 16 ) 
       LEFT JOIN likes AS Likes 
              ON ( likes.object_id = Image.id 
                   AND likes.object_type = 3 ) 
WHERE  Image.gallery_id = 31 

当我使用count时,它只返回1行。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您需要GROUP BY

SELECT Count(Message.id) AS subCount, 
       Count(likes.id), 
       Image.id, 
       Image.date_created, 
       Image.likes, 
       Image.path 
FROM   images AS Image 
       LEFT JOIN messages AS Message 
              ON ( Message.object_id = Image.id 
                   AND Message.msg_type = 16 ) 
       LEFT JOIN likes AS Likes 
              ON ( likes.object_id = Image.id 
                   AND likes.object_type = 3 ) 
WHERE  Image.gallery_id = 31 
GROUP  BY Image.id, 
          Image.date_created, 
          Image.likes, 
          Image.path