我有一张桌子:messages
具有这种结构:
`ID` // auto increment
`SenderUserID` // foreign key: `ID` from `User` table
`ReceiverUserID` // foreign key: `ID` from `User` table
`Message`
`DateCreated` // timestamp
我需要通过以下条件从表中获取不同的 ReceiverUserID:
- 发件人用户应该与收件人用户进行对话。
- 选择的不同
ReceiverUserID
应该给我们最后的DateCreated
信息。
因此,在结果中,我将按创建日期 DESC 排序用户最后一次对话。
当我在选择查询中不同时,mysql 返回第一条记录,但我需要DateCreated
选择的最大 `ReceiverUserID 才能获得结果顶部的最后一条消息。
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
很高兴知道这将与 facebook 留言板完全一样。
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
当前登录用户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`
我们在这部分有问题:当接收者用户回答发送者消息时,它没有返回我们在 11 和 13 之间的最后一次对话,它不会在结果中看到
结果:
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