1

我正在尝试创建一个 sql 查询,该查询将返回 imageId、该图像的总喜欢数以及当前用户是否喜欢该图像的布尔值。

到目前为止,我所拥有的是:

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 和总喜欢数非常有用。我不确定如何确定用户是否喜欢同一查询中的该图像。

提前致谢!

4

1 回答 1

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。

于 2013-05-27T16:15:20.020 回答