我有一个名为messages
的表,设置了这个:
`id` is the primary key.
`from` is the current user.
`to` is the receiver of the message.
`by` is the sender of the message.
`date` is the date of the message. its the time() function from php.
我想写一个语句来选择所有唯一的to
用户。另外,我想选择从from
发送到to
的最后一条消息,并按date
DESC
排序。我只有from
变量提供给查询。我有这个代码,但它只能部分工作。它不会在2个用户之间提取最新消息。
$get_messages = $mysqli->query("SELECT DISTINCT `id`, `from`, `to`, `by`, `date`, `message`, `seen` FROM `messages` GROUP BY `to` WHERE `from` = '$from' ORDER BY `date` DESC");
我在这里做错了什么?请帮忙!
答案 0 :(得分:2)
如果我理解正确,您希望to
用户在指定的from
用户上收到最新消息。
SELECT a.*
FROM messages a
INNER JOIN
(
SELECT m.to, MAX(date) max_date
FROM messages m
WHERE m.from = @from
GROUP BY m.to
) b ON a.to = b.to
AND a.date = b.max_date
WHERE a.from = @from
ORDER BY a.date DESC