三体电子书百度云:如何查询一个表中,各个分类的前面2条数据,用一条sql语句

来源:百度文库 编辑:查人人中国名人网 时间:2024/04/25 17:52:49
表结构 name,fl,id

比如:fl=1,前两条,fl1=2,前两条……

如何查询一个表中,各个分类的前面2条数据,用一条sql语句
帮助_li,的答案比较接近了,但是我的分类比较多,如果用union的话,查询语句很长,效率应该不是很好了!

biguoting,你好,游标怎么用呀,我没用过,能帮我找点资料吗?

select top 2 * from 表名 where f1=1;//这求出fl=1的前两条
select top 2 * from 表名 where f1=2//这求出fl=2的前两条
select top 2 * from 表名 where f1=1 union select top 2 * from 表名 where f1=2//求出fl=1的前两条并上fl=2的前两条

//不知道我明不明白你说的意思,我感觉我理解可能有误

select * from 表名 where 分类名 = '' or 分类名 = '' order by 排序字段 asc limit 条数总和(貌似只能用来查不同分类的相同条数,比如都是两条都是三条)

如你所愿,一条语句完成
select [name],[fl],[id] from t2 where [id] in ((select min([id])[id] from t2 group by [fl])union(select min([id])[id] from t2 where [id] not in (select min([id]) from t2 group by [fl]) group by [fl]))order by [fl],[id]

select top2 * from 表名 where 条件1
union select top2 * from 表名 where 条件2
union select top2 * from 表名 where 条件3

分类比较多的话考虑用存储过程(游标)

select top2 * from 表名 where 条件1 and 条件2