0

我有一个包含(id:Int,userName:Varchar,roomName:Varchar,read:Boolean)的表,我想做的是选择用户名和roomName分组的读取次数。例如,如果我有这个值:

id UN  RN  read 
1   a   a   0
2   a   a   1
7   a   b   0
8   a   b   0
9   a   b   0
10  a   b   1
11  a   c   1

我希望我的查询返回:

a   a   1
a   b   3
a   c   0

但它只返回:

a   a   1
a   b   3

我尝试了这种方法:

select userName, roomName, 
        case when count(`read`) > 0 then  count(`read`) end as x 
from message 
where userName = "a" 
   && `read` = false  
group by roomName ;

还有这个:

select userName, roomName, 
        if(count(`read`) = 0, 0,count('read'))  
from message 
where userName = "a" 
   && `read` = false  
group by roomName ;

但它们都不起作用。我应该如何改变它?

4

1 回答 1

0

您需要条件聚合。为此,您需要删除readfromwhere子句上的过滤器(否则没有reads 的房间将被过滤掉):

select userName, roomName, sum(read) as x 
from message 
where userName = 'a'  
group by userName, roomName;

请注意,声明字符串文字的标准语法是使用单引号(MySQL 允许双引号,但在 SQL 标准中它们是用来定义标识符的,所以我不建议使用它们)。

于 2020-06-24T09:29:42.987 回答