0

我有一张桌子

________________________________________________________________________________
|                         Message                                               |
|_______________________________________________________________________________|
| ID(INT) |  Text(TEXT) |read(TINYINT(0/1)) |deleted(TINYINT(0/1))|  User_id    |
| 1       | How Are You?|      0            |        0            |    6        |
| 2       | Fine        |      0            |        1            |    4        |
| 3       | Message 3   |      1            |        0            |    6        |
| 4       | Message 4   |      0            |        1            |    6        |
| 5       | Message 5   |      1            |        0            |    5        |
|_________|_____________|___________________|_____________________|_____________|

现在我想选择 user_id=6 的消息,并分别选择 read=0 和 read=1 的列数。我知道这可以通过命令分组来完成,我目前使用两个 sql 查询来完成。可能有人加入他们合二为一

select message,count(*) from message where User_id=6 and read=0 group by id;//for unread message
select message,count(*) from message where User_id=6 and read=1 group by id;//for read message
4

3 回答 3

3

加入你的两个查询很容易,但我没有得到你真正想要的。

SELECT `message`, count(*) AS `cnt` , `read`
FROM message 
WHERE `User_id`=6 
  AND `read` IN ( 0, 1 ) 
GROUP BY `id` , `read`;
于 2012-06-12T08:54:29.890 回答
1

你为什么不

select
  message,
  sum(read) as num_read,
  sum(case read when 0 then 1 else 0 end) as num_unread
from message
where user_id = 6
group by user_id

? 您可以逐行删除 where 或 group,具体取决于您的实际需要和 SQL 实现。

于 2012-06-12T09:05:03.353 回答
0

尝试这个:

select read,id,count(*) 
  from message 
 where user_id = 6 and read in (0,1) group by read,id
于 2012-06-12T08:58:54.527 回答