MySQL查询top N记录
下面以查询每门课程分数最高的学生以及成绩为例,演示如何查询 top N记录。下图是测试数据,表结构和相关 insert 脚本见《常用SQL之日期格式化和查询重复数据》。
使用自连接【推荐】
select a.name,a.course,a.score from test1 a,
(select course,max(score) score from test1 group by course) b
WHERE a.course=b.course and a.score=b.score;
执行后,结果集如下:
使用相关子查询
select name,course,score from test1 a
where a.score=(select max(score) from test1 where a.course=test1.course);
或者
select name,course,score from test1 a
where not exists(select 1 from test1 where a.course=course and a.score < score);
或者
select a.* from test1 a
where 1>(select count(*) from test1 where course=a.course and score>a.score);
结果集同上图。需要注意的是如果最高分有多条,会全部查出!
TOP N(N>1)
以N=2为例,演示如何查询TOP N(N>1)。
使用union all
如果结果集比较小,可以用程序查询单个分组结果后拼凑,也可以使用 union all。
(select name,course,score from test1 where course='语文' order by score desc limit 2)
union all
(select name,course,score from test1 where course='数学' order by score desc limit 2)
union all
(select name,course,score from test1 where course='英语' order by score desc limit 2);
自身左连接
select a.name,a.course,a.score
from test1 a left join test1 b on a.course=b.course and a.score<b.score
group by a.name,a.course,a.score
having count(b.id)<2
order by a.course,a.score desc;
两个表做连接查询,笛卡尔积,然后用having count(b.id)筛选出比当前条数大的条数。
自关联+count()
select a.* from test1 a
where 2>(select count(*) from test1 where course=a.course and score>a.score)
order by a.course,a.score desc;
思路就是判断每一条记录,比a中当前记录大的条数是否为2,如果有2条比较大,则符合。筛选出全部记录,最后按课程和学分排序。但是子查询进行了n次count(*)计算,因此性能极差。
半连接+count()+having
select * from test1 a where exists(select count(*) as sum from
test1 b where b.course=a.course and b.score>a.score having sum <2)
order by a.course,a.score desc;
读后有收获,小礼物走一走,请作者喝咖啡。

作者:楼兰胡杨
本文版权归作者和博客园共有,欢迎转载,但请注明原文链接,并保留此段声明,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南