MySQL Group by和Order

时间:2012-08-31 15:27:59

标签: mysql sql

我正在尝试将对话等消息分组并仅显示来自对话的最新消息,因此我需要time列中编号最大的消息。

这是我的疑问:

SELECT * 
FROM console_msgs 
WHERE `to` = $user[id] 
GROUP BY `from` 
ORDER BY time DESC

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

你想要groupwise maximum

SELECT console_msgs.*
FROM   console_msgs NATURAL JOIN (
         SELECT   MAX(time) AS time
         FROM     console_msgs
         WHERE    `to` = $user[id]
         GROUP BY `from`
       ) t
WHERE  `to` = $user[id]

答案 1 :(得分:0)

我不太了解您需要返回的结果集,但我认为您需要使用LIMIT关键字才能返回最高结果。试一试:

SELECT from, MAX(time) 
FROM console_msgs 
WHERE `to` = $user[id] 
GROUP BY `from` 
ORDER BY time DESC
LIMIT 1

答案 2 :(得分:0)

您不希望使用GROUP BY来实现我认为您所要求的内容。你只想要多个订单

SELECT * 
FROM console_msgs 
WHERE `to` = $user[id] 
ORDER BY `from`, time DESC