mysql 查询 uid 按time 最新的前3条记录

也就是 查询某个字段的前3条记录

 

select uid,time from 表名 order by time desc limit 0,3

再按 uid 分组

如下:

SELECT uid,time from table_x as tbx_o 
where 3 > (
    SELECT count(*) from table_x as tbx_i 
    where tbx_o.uid = tbx_i.uid and tbx_o.time < tbx_i.time
) ORDER BY uid;

# 更新的语句
select table_out.uid,sum(table_out.score) from (
	SELECT uid,time,score from table_x as tbx_o 
	where 3 > (
	    SELECT count(*) from table_x as tbx_i 
	    where tbx_o.uid = tbx_i.uid and tbx_o.time < tbx_i.time
	) ORDER BY uid
) as table_out
group by table_out.uid
order by 2 desc;

 

order by 子句后跟一个 limit n,就是限制前 n 条。

您好,我是有问必答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632