从MySQL获取未读消息的数量

时间:2015-05-11 13:29:52

标签: mysql

我正在开发Android聊天应用程序。 我有两张桌子。

Table: chats

id  sender_id receiver_id message  read_status  sender_name

1    22         11        hi..      1          raaj
2    22         11        hey.      1          raaj
3    22         11        nice.     0          raaj
4    22         11        wow       0          raaj
5    22         11        thanx     0          raaj
6    11         22        yup       0          deep
7    33         11        hi..      1          sanju
Table read:

id   status
0     unread
1     read 
About users
id--> 22 -->raaj

id-->11--->deep

id--->33--->sanju

我必须得到DISTINCT sender_id , sender_name , no. of unread messages WHERE sender_id != '11'

我需要这样的结果:

sender_id   sender_name  no_of_unread_messages
22          raaj            3
33          sanju           0   

如何使用一个查询在MySQL中执行此操作?

1 个答案:

答案 0 :(得分:1)

SELECT sender_id, sender_name, COUNT(*) no_of_unread_messages
FROM chats
WHERE sender_id != 11
  AND read_status=0
GROUP BY sender_id

如果你需要SUM = 0的记录,试试这个:

SELECT sender_id, sender_name, SUM(IF(read_status=0,1,0)) no_of_unread_messages
FROM chats
WHERE sender_id != 11
GROUP BY sender_id