1

我有以下表结构

在此处输入图像描述

我希望结果是

在此处输入图像描述

这是我尝试过的查询

select * from table where userid IN(201,202,203,204,205)
group by userid
order by messageid desc

但我力求根据 messageid 获取最新记录。我需要在一个查询中写这个,因为我必须使用 order by 子句

请解释我的错误并提供解决方案

4

2 回答 2

2
SELECT yourtable.*
FROM
  yourtable INNER JOIN (SELECT userid, MAX(messageid) max_messageid
                        FROM yourtable
                        WHERE userid IN (201,202,203,204,205)
                        GROUP BY userid) mx
  ON yourtable.messageid=mx.max_messageid
     AND yourtable.userid=mx.userid
于 2013-10-17T16:16:34.577 回答
2

如果我正确理解您的问题,您可以使用max的将表格连接到自身:messageid

select t.messageid, t.userid, t.data
from yourtable t
  join (
    select max(messageid) maxmessageid, userid
    from yourtable
    where userid in (201,202,203,204,205)
    group by userid
    ) t2 on t.userid = t2.userid and t.messageid = t2.maxmessageid
order by t.messageid desc

编辑:这是使用的替代方法IN

select messageid, userid, data
from yourtable
where messageid in (
    select max(messageid) maxmessageid
    from yourtable
    where userid in (201,202,203,204,205)
    group by userid
    ) 
order by messageid desc
于 2013-10-17T16:16:41.480 回答