Table:
id sender receiver message
1 14 16 1st message from 14 to 16
2 16 14 1st message from 16 to 14
3 16 14 2nd message from 16 to 14
4 14 16 2nd message from 14 to 16
5 15 14 1st message from 15 to 14
6 15 14 2nd message from 15 to 14
7 14 16 3rd message from 14 to 16
8 14 16 4th message from 14 to 16
9 14 15 1st message from 14 to 15
10 14 15 2nd message from 14 to 15
Now, what I am trying to do here to is to group the messages for one user (as a receiver), but the problem is that I want the latest entry regardless of who sent the message.
Attempt 1:
SELECT c2. *
FROM (
SELECT max( id ) `id`
FROM tbl_msg
GROUP BY `sender`
)c1
INNER JOIN tbl_msg c2 ON c1.id = c2.id
WHERE `receiver` =14
GROUP BY `sender`
Result:
id sender receiver message
6 15 14 2nd message from 15 to 14
3 16 14 2nd message from 16 to 14
Here the result is that each last message is sent to user 14. It obviously won't include the message sent by user 14.
Again, I can't use an addtional GROUP BY
on receiver
, because then it would only include the last entry sent by user 14.
Expected output:
id sender receiver message
10 14 15 2nd message from 14 to 15
8 14 16 4th message from 14 to 16
Now in the above, sender
in both the entries are 14, but it can be any user.
In simple words:,
I want to retrieve the last message in a conversation between A and B, regardless of who said it.
Is using GROUP BY
here a wrong approach?
N.B. The questions below are somewhat similiar to this question with the exception that they deal with only one criteria. But here, I have two (i.e. the user can be either a sender or a receiver). This is the part where I am stuck at.
Retrieving the last record in each group
MySQL - Control which row is returned by a group by