【转】Mysql相关子查询&&MySQL获取分组后的TOP N记录

https://www.cnblogs.com/Yiran583/p/6743870.html

select * from test1 a where 2 > (select count(*) from test1 where course=a.course and score>a.score)

自己的理解:

先取出一个score,通过子查询去取同一个表里的所有score去和这个score做对比:

如果子查询找不出比a.score大的,即符合条件的count=0,那么此时a.score就是最大的。符合条件(score值前两位)

如果子查询找出来一个比a.score大的,即符合条件的count=1,那么此时a.score就是第二大的。(符合条件,score值前两位)

其他实现:

https://www.cnblogs.com/prayer21/p/6029694.html

另外的案例:

https://blog.csdn.net/come_on_air/article/details/72902592

我的实现:(每个分类找出价格最高的有效的两个商品)

select m1.goods_id,m1.cat_id,m1.price
from mygoods m1
where m1.status=1
and (select count(1) from mygoods where cat_id=m1.cat_id and price>m1.price and status=1) < 2
order by m1.cat_id,m1.price desc

原文地址:https://www.cnblogs.com/byron0918/p/9555470.html