MySQL:按ID排序分组结果

时间:2016-09-24 22:42:13

标签: php mysql group-by sql-order-by

我在分组时按ID排序结果时遇到一些问题:

$get_seen_messages = mysql_query("SELECT * 
                                  FROM chat 
                                  WHERE userto='$login_cookie' 
                                    AND status='seen' 
                                  GROUP BY userfrom 
                                  ORDER BY id DESC");

请帮帮我:D

2 个答案:

答案 0 :(得分:1)

哪个id?您应该从不使用SELECT *GROUP BY。使用GROUP BY时,所有未加聚合的列都应位于GROUP BY中。所以,这是一个正确形成的查询

SELECT userfrom, MAX(id) as id
FROM chat
WHERE userto = '$login_cookie' AND status = 'seen'
GROUP BY userfrom
ORDER BY MAX(id) DESC;

我怀疑,您希望每个userfrom的聊天最新一行。在这种情况下,正确形成的查询如下所示:

select c.*
from chat c
where userto = '$login_cookie' and status = 'seen' and
      id = (select max(c2.id)
            from chat c2
            where c2.userto = c.userto and c2.status = c.status
           );

答案 1 :(得分:0)

您是否尝试过subquerys?

$get_seen_messages = mysql_query("
    SELECT * FROM
        (SELECT * 
            FROM chat 
            WHERE userto='$login_cookie' 
            AND status='seen' 
            GROUP BY userfrom) as subquery 
    ORDER BY id DESC");