我有一张桌子
________________________________________________________________________________
| 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的列数。我知道这可以通过逐个命令来完成,而iam目前正在使用两个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
答案 0 :(得分:3)
加入你的两个查询非常简单,但我没有得到你真正想要的东西。
SELECT `message`, count(*) AS `cnt` , `read`
FROM message
WHERE `User_id`=6
AND `read` IN ( 0, 1 )
GROUP BY `id` , `read`;
答案 1 :(得分: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实现。
答案 2 :(得分:0)
试试这个:
select read,id,count(*)
from message
where user_id = 6 and read in (0,1) group by read,id