如果一个Mysql库表达到百万数量级,那么使用普通的SQL语句写法会导致速度逐渐慢到难以忍受,下面是一种可以保证速度的写法。
假设表名称为entity,含有数百万条记录,有一个主键为自增id,另外两列为entityName和url,现在要读取表中的entityName
int total = getTotalCount();//获取记录总数
int limit = 1000;//每次读取的记录个数
int fetchSize = (total + limit - 1) / limit;
for(int i = 0; i < fetchSize; ++i) {//若程序中断,可以修改i的初始值,继续从断掉的地方继续运行
int startIndex = i * limit;
if (startIndex >= 10000) {
sql = "select entityName from entity where id >= (select id from entity order by id asc limit "
+ startIndex + ",1) limit " + limit;
} else {
sql = "select entityName from entity order by id asc limit "
+ startIndex + ", " + limit;
}
//其余代码略
}
上述代码段的if和else提供了两种查询方法,if中为效率更高的分页查询写法,它先对表中的记录进行定位,然后从这个位置开始取数据;else中即为普通的查询写法,由limit限定每次查询的部分,随着数据的顺序读取,需要跨越的数据块越来越大,导致速度越来越慢。实际的应用表明在整个的查询过程中,第一种方法的速度比较快且稳定。
注意:在写select语句的时候,需要用到哪几列就select哪几列,比select *的效率高