项目中用到了数据库,其中一个表有33万条数据。对这个表进行查询,执行类似“SELECT * FROM table1 where ds_key like 'asd%%'”这样的语句,在我的Touch上用了大概11秒,体验很差。
调查发现,虽然已经对table1增加了索引,但是在实际执行的时候,如果查询条件包含LIKE,就不会使用索引。
想知道查询是不是用了索引,可以参考http://www.sqlite.org/eqp.html这个链接提供的方法进行验证。
而改成“SELECT * FROM table1 where ds_key >= 'asd' and ds_key < 'ase'”这样的语句,查询时就会使用到索引,花费时间只有零点几秒,效率提高了几十倍。
当然,这只针对查询以某个字符串开头的记录的情况,而对于like '%%asd%%'这样的就没法优化了。
下面的问题就是如何获得输入关键词的“下一个比它大”的词了。
考虑到字段中还包含中文,最终我写了这样一段代码:
复制代码
-
//获取字符串的下一个比它大的字符串
-
- (NSString*)nextStringAfterString:(NSString*)text
-
{
-
NSString *nextString = nil;
-
int length = text.length;
-
NSString *prefixString = [text substringToIndex:length - 1];
-
NSString *lastString = [text substringFromIndex:length - 1];
-
const char* lastChar = [lastString UTF8String];
-
int lastLength = strlen(lastChar);
-
if (lastLength == 1) {//ASCII
-
char newChar1[2];
-
newChar1[0] = lastChar[0] + 1;
-
newChar1[1] = 0;
-
NSString *newString1 = [NSString stringWithUTF8String:newChar1];
-
nextString = [prefixString stringByAppendingString:newString1];
-
}
-
else if (lastLength == 3) {//中文
-
char newChar2[4];
-
newChar2[0] = lastChar[0];
-
newChar2[1] = lastChar[1];
-
newChar2[2] = lastChar[2] + 1;
-
newChar2[3] = 0;
-
NSString *newString2 = [NSString stringWithUTF8String:newChar2];
-
nextString = [prefixString stringByAppendingString:newString2];
-
}
-
return nextString;
-
}
如果返回的是nil,还是使用LIKE查询,不过这种情况貌似不会出现。