本文介绍了如何从每组MySql中选择前N条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个表,我想从该列的sub_category_id
列中的每个组中获取前N个项目.如果我设置N=10
,那么将从每个组中选择前10
行,或者如果我设置N=5
,则将从每个组中选择前5行.请帮助我.
I have a table where i want to get top N items from each group on the base of column sub_category_id
.If i set N=10
that would select first 10
rows from each group or if i set N=5
then that would select top `5 rows from each group. Please help me.
推荐答案
有多种方法可以做到这一点.这是使用相关子查询的一个:
There are multiple ways to do this. Here is one using a correlated subquery:
select t.*
from t
where (select count(*)
from t t2
where t2.sub_category_id = t.sub_category_id and t2.id <= t.id
) <= 10;
这篇关于如何从每组MySql中选择前N条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!