Mysql COUNT和IF用法

时间:2012-09-08 14:04:07

标签: mysql sql

我有MySQL表格结构:

| uid     |   itemid
| -------------------
| 1001    |   9999
| 1001    |   8888
| 2002    |   8888
| ...     |   ...

uid itemid 不是唯一列。 Bun uid + itemid是独特的组合。

我需要按itemid计算行数。我使用下一个查询:

SELECT itemid, COUNT(*) 
FROM unlikes 
WHERE itemid IN ('9999', '8888') GROUP BY itemid;

这很有效!

接下来,我需要知道哪一行有具体的uid。我用:

SELECT itemid, COUNT(*), IF (uid = '1001', TRUE, FALSE) toggled 
FROM unlikes 
WHERE itemid IN ('9999', '8888') GROUP BY itemid;'

不行。如果我有多个itemid = 8888,而不是toggled = FALSE。如果组中的一个有uid = 1001;

,我需要切换= TRUE

1 个答案:

答案 0 :(得分:1)

SELECT itemid, COUNT(*), 
CASE WHEN uid = 1001 THEN TRUE ELSE FALSE end AS toggled 
FROM unlikes 
WHERE itemid IN ('9999', '8888') GROUP BY itemid;