I have a table: messages with this structure:
`ID` // auto increment
`SenderUserID` // foreign key: `ID` from `User` table
`ReceiverUserID` // foreign key: `ID` from `User` table
`Message`
`DateCreated` // timestamp
I need to get distinct ReceiverUserIDs from table by this conditions:
- Sender user should have conversations with receiver users.
- Selected distinct
ReceiverUserIDshould give us lastDateCreatedmessage.
So in the results, I’ll have user last conversations ordered by creation date DESC.
When I distinct in select query, mysql return a first record, but I need maximum DateCreated for selected `ReceiverUserID to get last message in top of results.
SELECT DISTINCT `m`.`ReceiverUserID` AS `ID` FROM `messages` `m`
WHERE (`m`.`SenderUserID` = :UserID OR `m`.`ReceiverUserID` = :UserID)
ORDER BY `m`.`DateCreated` DESC
//:UserID means LogedInUserID
It is good to know It will be exactly like facebook messages board.
ID, SenderUserID, ReceiverUserID, Message, DateCreated
1, 12, 11, 'Hi admin', 2012-10-24 11:07:00
2, 11, 12, 'Hi guy', 2012-10-24 11:08:00
3, 11, 13, 'Hello dear customer', 2012-10-24 11:12:00
4, 11, 13, 'Are you there?', 2012-10-24 11:13:00
5, 13, 11, 'Hiiii', 2012-10-24 11:14:00 // last conversation betwen 11 & 13
Current logedin user id: 11
SELECT `m`.`ReceiverUserID` AS `ID`, MAX(`m`.`DateCreated`) as `lastmsg`
FROM `messages` `m` WHERE (`m`.`SenderUserID` = 11 OR `m`.`ReceiverUserID` = 11)
GROUP BY `m`.`ReceiverUserID`
We have problem in this section:
It is not return our last conversation between 11 and 13 when receiver user answered the sender message, It will be not seen in results
Results:
ID, lastmsg
12, 2012-10-24 11:08:00
13, 2012-10-24 11:13:00 // Should be: 13, 2012-10-24 11:14:00
As I mentioned you have to do the same with SenderUserID…