2013-05-27 45 views
1

我試圖創建一個sql查詢,它將返回imageId,喜歡這個圖像的總數,也是當前用戶是否喜歡該圖像的布爾值。如何獲得布爾結果SQL查詢

我至今是:

Select i.imageId, count(l.likeId) as numOfLikes 
FROM Images as i LEFT JOIN Likes as l USING (imageID) 
WHERE i.userId = '16' 
GROUP BY i.imageId 
ORDER BY i.dateCreated DESC 

其中的imageIds和喜歡爲每個圖像總數的偉大工程。我不確定我如何能夠確定用戶是否在同一查詢中喜歡該圖像。

在此先感謝!

+1

你就不能檢查,如果喜歡的數量大於0? –

回答

1

像這樣的東西應該工作。

Select i.imageId, count(l.likeId) as numOfLikes 
, count(likes2.*) LikesByUser 
FROM Images as i LEFT JOIN Likes as l USING (imageID) 
left join likes likes2 using (imageID, UserId) 
WHERE i.userId = '16' 
GROUP BY i.imageId 
ORDER BY i.dateCreated DESC 

LikesByUser應該是0或1

+0

非常感謝! – NSDavidObject