我从表中获取数据并按另一个表中的列对它们进行排序。以下是我的询问。
$query = "SELECT Chatroom.ChatID, Chatroom.User1, Chatroom.User2 FROM `Chatroom` JOIN `Messages` ON Chatroom.ChatID = Messages.ChatID WHERE User1 = ? OR User2 = ? ORDER BY Messages.MessageDate";
假设两个人之间有聊天,他们已经发了10次消息。当我真的想要1个结果时,我会得到10个结果。我意识到它正在循环播放消息,因为我在chatID上加入了它们,但我这样做是为了获取日期。
有没有更好的方法来获取此功能,或者是否可以轻松调整我的查询?
答案 0 :(得分:1)
如果您正在使用MySQL,可以尝试一下吗?
SELECT c.ChatID, c.User1, c.User2
FROM Chatroom AS c
JOIN (
SELECT mx.*
FROM Messages AS mx
WHERE mx.ChatID = c.ChatID
ORDER BY mx.MessageDate
LIMIT 1
) AS m ON m.ChatID = c.ChatID
WHERE c.User1 = ?
OR c.User2 = ?
ORDER BY m.MessageDate;
试试这个吗?
SELECT c.ChatID, c.User1, c.User2
FROM Messages AS m
JOIN Chatroom AS c on c.ChatID = m.ChatID
WHERE (c.User1 = ? OR c.User2 = ?)
GROUP BY c.ChatID
ORDER BY m.MessageDate