2013-04-17 54 views
0

我只想統計所有的子註釋以及統計所有屬於圖庫的圖像的所有喜歡。正確使用計數

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 

當我使用計數,它只返回1行。有任何想法嗎?

回答

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 
+0

*嘆氣*。我想創建一個MySQL分支,每次在沒有GROUP BY的情況下使用聚合並在SELECT或ONLY_FULL_GROUP_BY被禁用時生成一個警告錯誤消息 –

+0

@MichaelBerkowski'ONLY_FULL_GROUP_BY'應默認啓用。 – Kermit

+0

謝謝。我知道。腦屁。 – user1274457