T1:
+--------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+------------------+------+-----+---------+----------------+
| id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| message_text | text | NO | | NULL | |
| sender_id | int(11) unsigned | NO | MUL | NULL | |
| receiver_id | int(11) unsigned | NO | MUL | NULL | |
| pair_id | int(11) unsigned | NO | MUL | NULL | |
| time_stamp | bigint(20) | NO | | NULL | |
| is_read | tinyint(1) | NO | | 0 | |
+--------------+------------------+------+-----+---------+----------------+
T2:
+----------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+------------------+------+-----+---------+----------------+
| id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| user_id1 | int(11) unsigned | NO | MUL | NULL | |
| user_id2 | int(11) unsigned | NO | MUL | NULL | |
+----------------+------------------+------+-----+---------+----------------+
I want to fetch the records from this table like:
pair_id | message_text | sender_id | receiver_id | count_unread
This table(T1) stores the messages where:
message_text: message,
sender_id: sender,
receiver_id: receiver,
pair_id: This is the foreign key referring to an other table that keeps the chatting user pairs i.e. T2,
is_read: 0 if unread, otherwise 1.
Now, i want all the pairs with the corresponding unread messages count. Also, the pair must get displayed even if the count is zero. Thanks in advance.
Query i have tried:
SELECT all_messages.id,
all_messages.sender_id,
all_messages.receiver_id,
count(all_messages.id) AS unread_msg_count
FROM all_messages
JOIN message_pairs
ON message_pairs.id = all_messages.pair_id
WHERE all_messages.receiver_id = :receiver_id
AND is_read = 0
GROUP BY
pair_id