mysql 分組查詢每組的最新一條資料

2022-09-22 05:18:09 字數 1089 閱讀 8883

1.原始資料

學生成績表

2.想要獲取每個考生最新的考試成績,網上的例子

select a.* from (select * from scoreinfo order by scoreinfo.createtime desc ) as a

group by a.snum

order by a.createtime;

執行結果為

很明顯執行結果不對,通過網上查詢發現

mysql5.7時,子查詢的排序已經變為無效了

想要使排序生效,必須執行 limit 條數限制

select a.* from (select * from scoreinfo order by scoreinfo.createtime desc limit 1000) as a

group by a.snum

order by a.createtime;

執行結果為想要的資料

方法2

select * from scoreinfo

join (select snum, max(createtime) as createtime from scoreinfo group by scoreinfo.snum) as a

where scoreinfo.snum=a.snum&&scoreinfo.createtime=a.createtime;

執行結果

參考:

mysql分組查詢最新資料

select user id,sbp,dbp,pulse from p bp as a,select max id as id,max measure at as measure at from p bp as b group by user id as b where a.id b.id and ...

MYSQL 分組查詢最新的資料

第一種前提是資料表設計id自增select from t user where id in select max id from t user group by user id 第二種對子查詢進行limit限制,適用於明確資料量不會超過多少的場景,否則查不到全部資料select from selec...

分組查詢 每組查詢前5條

按班級分組查詢,每組查詢出5條資料。資料表結構如下 drop table if exists test1 create table test1 id int 11 not null auto increment,class int 11 default null comment 班級 name te...