mysql检查组中是否存在值

时间:2013-01-15 14:29:47

标签: mysql sql group-by aggregate

我有一个名为votes的表格,其中包含idimage_iduser_idtime列。

如果特定user_id是每个image_id的投票之一,如何在结果中添加bool?

SELECT image_id,
count(image_id) as vote_count
FROM votes
GROUP BY image_id 
ORDER BY vote_count DESC

我已尝试if(user_id = 18, 1, 0) as have_voted,但它不适用于每个image_id

1 个答案:

答案 0 :(得分:7)

如何对user_id所需的所有行进行求和,并检查此总和是否大于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