我有一个页面显示与您聊天的人员列表。目前它正在显示您聊天的人和OLDEST消息。但是,它应该显示最新的消息。这是查询:
SELECT * FROM post
WHERE fk_user_to = '$userid'
GROUP BY fk_user_from
ORDER BY datotime DESC
和表结构
post_id || fk_user_to || fk_user_from || message || datotime
答案 0 :(得分:2)
这就解决了:
SELECT * FROM
(SELECT * FROM post ORDER BY datotime DESC) as inv
WHERE fk_user_to = '$userid'
GROUP BY fk_user_from
ORDER BY datotime DESC
答案 1 :(得分:0)
它并没有真正发挥作用。您永远无法确定GROUP BY选择的行,因此在其上放置ORDER BY将具有不可预测的输出。此外,你不能通过BEFORE之前下订单。
试试这个:
SELECT *,MAX(datotime) AS dt fk_user_from
FROM post
WHERE fk_user_to = '$userid'
GROUP BY fk_user_from
ORDER BY dt
答案 2 :(得分:0)
我认为没有简单的SQL解决方案。如果数据库系统允许子查询,则可以执行子查询,如
SELECT fk_user_from AS id, MAX(dateotime) AS newest_timestamp FROM post WHERE fk_user_to = '$userid'
然后使用两个字段作为键再次从post
中进行选择。
在MySQL中可能是这样的:
SELECT * FROM post P1
JOIN (
SELECT fk_user_from, MAX(dateotime) AS newest_dateotime
FROM post
WHERE fk_user_to = '$userid'
GROUP BY fk_user_from
) AS P2
ON P1.fk_user_from=P2.fk_user_from
AND P1.datotime =P2.newest_dateotime
WHERE P1.fk_user_to = '$userid'