这是我的查询
"SELECT * FROM messages WHERE to_user = :user ORDER BY time ASC"
问题是它会忽略from_user
列并显示来自单个用户的多条消息,我只想显示from_user
列中每个用户的最后一条消息,并显示发送给在to_user
列中记录的用户
如果from_user
已经发送了一条消息,如何忽略其他消息?
我只选择最后一条消息from_user
至to_user
我尝试了限制,但它只选择了from_user
列中的一条用户消息,我需要按to_user
进行选择,但会返回from_user
列中的所有单个用户消息>
PHP代码
//$sql = "SELECT * FROM messages WHERE to_user = :user ORDER BY time ASC";
$sql = "SELECT DISTINCT from_user, messages.* FROM messages WHERE to_user = :user ORDER BY time ASC";
$stm = $conexao_pdo->prepare($sql);
$stm->bindParam(':user', $user_logged);
$stm->execute();
答案 0 :(得分:0)
据我所知,我相信您必须使用GROUP BY
操作者,并且解决方案应如下所示:
SELECT Max(time), messages.* FROM messages WHERE to_user = :user
Group BY from_user
ORDER BY time ASC
(您的样本数据应包含一些相关内容)
编辑: 不要在SELECT中混合使用汇总和非汇总值,请参阅下面的评论。
SELECT
messages.*
FROM
messages
JOIN
(SELECT
from_user, MAX(time) MAX_TIME
FROM
messages
WHERE
to_user = :user
GROUP BY
from_user) MAX_QUERY
ON messages.from_user = MAX_QUERY.from_user
AND messages.time = MAX_QUERY.MAX_TIME
WHERE
to_user = :user;