SQL如何在不同分组中读取指定数量的数据?

来源:百度知道 编辑:UC知道 时间:2024/06/06 17:01:16
一个表
id|name|categories
1|a|1
2|b|1
3|c|2
4|d|3
......很多~~
我想在一次查询里面,按照categories排列,在每个categories里面都读取出5条数据(categories=1的读取5个,categories=2的也读取5个……)。

如何实现呢???
select top在MySQL下面不支持
能不能够提供一些 MySQL支持的代码???
目前有一个,但是个人觉得效率很低
select * from tb t where (select count(1)+1 from tb where categories = t.categories and name> t.name)>=5 order by categories asc

declare tt cursor for select categories from 表1 group by categories
open tt
declare @categories varchar(50)
fetch next from tt into @categories
while(@@fetch_status = 0)
begin
select top 5 * into 表2 from 表1 where categories = @categories
fetch next from tt into @categories
end
deallocate tt

通过 select * from 表2 order by categories 可以得到你想要的数据,其他的你自己加工一下,相信你应该看得懂

select top 5 * from table_name order by categories