MySQL选择GROUP BY命令

时间:2011-12-19 01:32:56

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

我有一个mysql语句

SELECT * 
FROM tbl_messages 
WHERE to_user_id = '$user_id' OR from_user_id = '$user_id' 
GROUP BY from_user_id 
ORDER BY date_sent DESC

它产生了正确的结果,但它们的顺序不正确。

分组效果很好但是在组中显示的记录是第一个记录在数据库中的记录,但我希望在每个组中显示最新记录。

有没有办法为每个组显示最新记录?

2011-12-19 12:16:25 This is the first message
2011-12-19 12:18:20 This is the second message
2011-12-19 12:43:04 This is the third message

该组显示“这是第一条消息”,我希望“这是第三条消息”,因为这是最新的记录/消息。

干杯

4 个答案:

答案 0 :(得分:9)

这可能有效(但不能保证):

SELECT * 
FROM
  ( SELECT *
    FROM tbl_messages 
    WHERE to_user_id = '$user_id' OR from_user_id = '$user_id' 
    ORDER BY date_sent DESC
  ) tmp
GROUP BY from_user_id 
ORDER BY date_sent DESC

这应该有效:

SELECT t.* 
FROM 
    tbl_messages AS t
  JOIN
    ( SELECT from_user_id 
           , MAX(date_sent) AS max_date_sent
      FROM tbl_messages 
      WHERE to_user_id = '$user_id' OR from_user_id = '$user_id' 
      GROUP BY from_user_id 
    ) AS tg
    ON  (tg.from_user_id, tg.max_date_sent) = (t.from_user_id, t.date_sent)
ORDER BY t.date_sent DESC

答案 1 :(得分:8)

在ORDER BY之后执行GROUP BY,方法是使用GROUP BY包装查询:

SELECT t.* FROM (SELECT * FROM table ORDER BY time DESC) t GROUP BY t.from

答案 2 :(得分:2)

如果你的消息表有一个自动递增的主键,并且所有消息本质上是最高的数字是最近的日期...但是,因为我不知道,我将基于MAX (date_sent)而不是max(SomeIDKey),但原理是一样的。

select
      tm2.*
   from
      ( select tm1.from_user_id, 
               max( tm1.date_sent ) LatestMsgDate
           from tbl_messages tm1
           group by tm1.from_user_id ) MaxPerUser

      left join tbl_messages tm2
         on MaxPerUser.From_User_ID = tm2.From_User_ID
        AND MaxPerUser.LatestMsgDat = tm2.Date_Sent

   order by
      date_sent DESC

答案 3 :(得分:-1)

你的意思是这样的:

SELECT * FROM tbl_messages WHERE to_user_id = '$user_id' OR from_user_id = '$user_id' GROUP BY from_user_id ORDER BY from_user_id, date_sent DESC