mysql 实现 TOP n

#top N

select id,title,content,score,website_name,publish_time,url from 
(
SELECT id,title,content,score,website_name,publish_time,url, 
if(@cid=website_name,@rank:=@rank+1,@rank:=1) as ranking,
@cid:=website_name 
from (
SELECT id,title,content,0.5*(comments_count+reports_count) as score,website_name,publish_time,url 
from Table 
ORDER BY website_name,id DESC) t1,
(SELECT @cid:=null,@rank:=0)t2   #变量的初始化部分
) aa
where ranking<=N

参考 :

全网最全的mysql分组后取topN的解答 - 知乎 (zhihu.com)

posted @ 2022-09-07 16:59  cup_leo  阅读(65)  评论(0编辑  收藏  举报