topN 数据库查询

mysql 8.0 之前版本 

SELECT * FROM

(SELECT

a.*,

@rankid :=IF( @na = sid, @rankid + 1, 1 ) rankid,

@na := a.sid na FROM

sc a,

( SELECT @na = '', @rankid = 0 ) r

ORDER BYsid,score DESC ) AS b

GROUP BY b.sid,b.score,b.rankid

HAVING b.rankid <= 2;

8.0版本

你可能感兴趣的:(topN 数据库查询)