简体   繁体   中英

How to get a boolean result SQL Query

I'm trying to create an sql query which would return the imageId, total number of likes this image has, and also a boolean of whether or not the current user likes that image.

What I have so far is:

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

Which works great for the imageIds and total number of likes for each image. I'm not sure tho how I'd be able to determine whether or not the user likes that image within the same query.

Thanks in advance!

Something like this should work.

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 should be 0 or 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM