3

我有表包含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

4

1 回答 1

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
于 2013-01-23T07:22:29.890 回答