Mysql中limit的用法:在我们使用查询语句的时候,经常要返回前几条或者中间某几行数据,这个时候怎么办呢?不用担心,mysql已经为我们提供了这样一个功能。
mysql> SELECT * FROM table LIMIT 95,-1; // 检索记录行 96-last.
mysql> SELECT * FROM table LIMIT 5; //检索前 5 个记录行
Select * From cyclopedia Where ID>=(
Select Max(ID) From (
Select ID From cyclopedia Order By ID limit 90001
) As tmp
) limit 100;
Select * From cyclopedia Where ID>=(
Select Max(ID) From (
Select ID From cyclopedia Order By ID limit 90000,1
) As tmp
) limit 100;
第1句是先取了前90001条记录,取其中最大一个ID值作为起始标识,然后利用它可以快速定位下100条记录
第2句择是仅仅取90000条记录后1条,然后取ID值作起始标识定位下100条记录
第1句执行结果.100 rows in set (0.23) sec
第2句执行结果.100 rows in set (0.19) sec
Select ID From cyclopedia limit 90000,1
)limit 100;
Select Top 90001 Max(ID) From (
Select ID From cyclopedia Order By ID
) As tmp
)
Select ID From cyclopedia limit 90000
Select ID From cyclopedia limit 90000,1
的结果分别是:
90000 rows in set (0.36) sec
1 row in set (0.06) sec
而MS-SQL只能用Select Top 90000 ID From cyclopedia 执行时间是390ms,执行同样的操作时间也不及MySQL的360ms.
select * from yanxue8_visit limit 10,10
多次运行,时间保持在0.0004-0.0005之间
Select * From yanxue8_visit Where vid >=(
Select vid From yanxue8_visit Order By vid limit 10,1
) limit 10
多次运行,时间保持在0.0005-0.0006之间,主要是0.0006
结论:偏移offset较小的时候,直接使用limit较优。这个显示是子查询的原因。
2、offset大的时候。
select * from yanxue8_visit limit 10000,10
多次运行,时间保持在0.0187左右
Select * From yanxue8_visit Where vid >=(
Select vid From yanxue8_visit Order By vid limit 10000,1
) limit 10
多次运行,时间保持在0.0061左右,只有前者的1/3。可以预先offset越大,后者越优。
//如果只给定一个参数,它表示返回最大的记录行数目
android中使用方法基本同Mysql, 使用如下:
ContentResolver cr = context.getContentResolver();
String selection = Topic.OWNER_IDENTITY_ID + " = ? AND (private = 0) group by " + Topic.TID;String orderBy = Topic.DATE + " DESC limit " + pageSize + " offset " + page * 10;
return cr.query(Uri.parse(CIRCLE_URI + "/topic"), null, selection, new String[] {
uid
}, orderBy);
3万+




被折叠的 条评论
为什么被折叠?



