返回图像上喜欢和不喜欢的数量

时间:2013-01-23 07:19:14

标签: mysql sql sql-server tsql

我的表包含img_idlikes列。 例如:

 1  1
 1  1
 1  0
 2  0
 2  0
 3  1

所以在运行此查询时:

select img_id, count(likes)
from my_table
where likes = 1
group by img_id

这是结果:

1  2
3  1

我跑的时候:

select img_id, count(likes)
from my_table
where likes = 0
group by img_id

结果是:

1 1
2 2

我的问题是:

我如何在query1中返回img_id 2 = 0,我的意思是img_id = 2没有喜欢 也在查询2 img_id = 3没有不喜欢所以我需要返回3 - > 0

1 个答案:

答案 0 :(得分:9)

在MySQL和SQL Server中,

SELECT  img_id,
        SUM(CASE WHEN likes = 1 THEN 1 ELSE 0 END) totalLikes,
        SUM(CASE WHEN likes = 0 THEN 1 ELSE 0 END) totalDisLikes
FROM    tableName
GROUP   BY img_ID

或仅仅在MySQL中,

SELECT  img_id,
        SUM(likes = 1) totalLikes,
        SUM(likes = 0) totalDisLikes
FROM    tableName
GROUP   BY img_ID