仅显示每个用户的最后一条消息

时间:2016-03-22 08:39:47

标签: php mysql

enter image description here

朋友们,我想在这个表中显示每个用户的最后一条消息,假设$_SESSION['id']为1,所以我想显示每个用户的最后消息1或者用户1这里是我的查询:< / p>

SELECT * FROM message WHERE (msg_from='1') OR (msg_to='1') GROUP BY msg_from,msg_to ORDER BY MAX(msg_id) DESC

但是当我运行它时,它会显示来自用户的两条消息,这些消息位于msg_from列和msg_to列中,并且它不显示最后插入的消息,请大家,我需要帮助。

2 个答案:

答案 0 :(得分:0)

因为你是按MAX(msg_id) DESC订购的,所以你只需要第一个结果,因为它是最新的,那么你可能会做类似的事情

SELECT TOP 1 * FROM message where msg_id IN (SELECT msg_id FROM message WHERE (msg_from='1') OR (msg_to='1') GROUP BY msg_from,msg_to ORDER BY MAX(msg_id) DESC);

SELECT * FROM message where msg_id IN (SELECT msg_id FROM message WHERE (msg_from='1') OR (msg_to='1') GROUP BY msg_from,msg_to ORDER BY MAX(msg_id) DESC) LIMIT 1;

希望它有所帮助:)

答案 1 :(得分:0)

从其他人那里获取用户1的最后消息:

SELECT * FROM message WHERE msg_to = '1'
GROUP BY msg_from ORDER BY msg_date DESC

从用户1获取最后的消息给其他人:

SELECT * FROM message WHERE msg_from = '1'
GROUP BY msg_to ORDER BY msg_date DESC

我没有使用您的MAX(msg_id)来订购数据,而是使用日期来获取最新消息。