0

I must retrive all those who have sent messages to a given user and if the messages have not been read, return the number. I have two tables

users

| id_user| username | status |
|    1   |   user1  |   yes  |
|    2   |   user2  |   yes  |
|    3   |   user3  |   yes  |

messages

| id_message |id_sender|id_dest|    message  | read |
|     1      |    1    |   2   |   some text | yes  |
|     2      |    3    |   2   |   some text |  no  |
|     3      |    2    |   1   |   some text |  no  |

and I have this query

select id_sender,username, count(distinct   id_message) as nr_messages
            FROM messages
            INNER JOIN users
            ON id_sender = id_user
            WHERE id_dest=$dest and status='yes'
            GROUP by id_sender

I can count the number of messages for each user but I can not know how many are unread. I must have a number if the messages are unread and 0 i the user do not have unread messages. for example for user2

 sender: user3 (1 unread message)
 sender: user1 (0 unred message)

messages table is ~2000000 rows

6
  • I don't see receiver_id in the schema as you have in query. Commented Mar 7, 2015 at 16:05
  • 1
    Perhaps: sum(case when read = 'yes' then 0 else 1 end)... Commented Mar 7, 2015 at 16:06
  • Or shorthand mysql conditional sum as sum(read <>'yes') Commented Mar 7, 2015 at 16:07
  • yes my error I have update Commented Mar 7, 2015 at 16:09
  • @sgeddes I dont undestand your answer can you explain or make an example? thanks Commented Mar 7, 2015 at 16:11

1 Answer 1

1

If you need to count both read and unread at the same time, you can use conditional sum as

select 
m.id_sender,
u.username,
sum(m.`read` = 'yes') as read_messages,
sum(m.`read` <> 'yes') as unread_messages 
from messages m 
join users u on u.id_user = m.id_sender 
where m.id_dest = 2 
group by m.id_sender ;

For the above sample data you will get

+-----------+----------+---------------+-----------------+
| id_sender | username | read_messages | unread_messages |
+-----------+----------+---------------+-----------------+
|         1 | user1    |             1 |               0 |
|         3 | user3    |             0 |               1 |
+-----------+----------+---------------+-----------------+
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.