我希望最高值位于列表顶部

时间:2017-10-04 01:09:38

标签: php sql

所以我有这个查询并显示值,'时间'是整数,它经常通过点击更新,当它被更新时我想要在页面刷新时列表顶部的最高值si,但它是不,我想知道分组是否会影响查询?

$sql= "select * FROM message 
       where userid_to = '$UserLoggedIn' || userid_from = '$UserLoggedIn' 
       group by conversation_id 
       ORDER BY time DESC";

2 个答案:

答案 0 :(得分:0)

我认为你应该对子查询中的对话进行聚合,以找到每个对话的最近时间。然后返回到您的message表以获取完整的消息记录。我不确定您的订购出了什么问题,但您当前的查询不确定。

SELECT m1.*
FROM message m1
INNER JOIN
(
    SELECT conversation_id, MAX(time) AS max_time
    FROM message
    WHERE userid_to = '$UserLoggedIn' OR userid_from = '$UserLoggedIn' 
    GROUP BY conversation_id
) m2
    ON m1.conversation_id = m2.conversation_id AND
       m1.time = m2.max_time
ORDER BY
    m1.time DESC;

答案 1 :(得分:0)

我会尝试这样做:

SELECT *,  MAX(time) as time
FROM message 
WHERE userid_to = '$UserLoggedIn' OR userid_from = '$UserLoggedIn'
GROUP BY conversation_id;