I have a table called votes
with columns id
, image_id
, user_id
and time
.
How can I add a bool in the result for if a specific user_id
is one of the votes for each image_id
?
SELECT image_id,
count(image_id) as vote_count
FROM votes
GROUP BY image_id
ORDER BY vote_count DESC
I have tried if(user_id = 18, 1, 0) as have_voted
but it does not work for each image_id
.
What about summing all the rows where the user_id
is the one you want, and checking if this sum is greater than 0?
SELECT image_id,
count(image_id) as vote_count,
SUM(IF(user_id = 18,1,0)) > 0 AS hasUser18
FROM votes
GROUP BY image_id
ORDER BY vote_count DESC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With