我的数据库中有一个表
SenderId ReceiverId Message DateAndTime
int(11) int(11) varchar(200) DATETIME
我想为对话风格的已登录用户排序所有消息。记录的用户之间的消息说UserA和UserB,UserC应该如下所示:
UserA UserB Sent
UserA UserB Sent
UserB UserA Received
UserA UserC Sent
UserC UserA Received
UserA UserC Sent
UserD UserA Receied
UserA UserD Sent
我已经尝试过这个查询,但结果并不像我期望的那样
SELECT * FROM messages WHERE SenderId like ? or ReceiverId like ? order by senderId, dateAndDate;
答案 0 :(得分:1)
这可能有用。它不是按时间排序,而是由参与者排序。
SELECT CONCAT(LEAST(SenderID, ReceiverId), '-', GREATEST(SenderID, ReceiverId)) AS conversation
, SenderID, ReceiverID, Message, DateAndTime
FROM messages
WHERE SenderID = ? OR ReceiverId =?
ORDER BY conversation, DateAndTime DESC;
答案 1 :(得分:0)
这应该可以解决问题。
SELECT SenderId, ReceiverId, Message, DateAndTime, CASE WHEN SenderId=1 THEN ReceiverId Else SenderId END as Optional from messages where SenderId = 1 or ReceiverId=1 order by Optional, DateAndTime desc;
假设Logged UserID为1,请改用占位符。