sqlite数据库中col的一些值:
a1b2
a2b3
a1b10
a10b1
如果在SQL中使用order by
,它将是:
a10b1
a1b10
a1b2
a2b3
我希望像NSNumericSearch
这样的objc:
a1b2
a1b10
a2b3
a10b1
如何编写SQL语句?
答案 0 :(得分:3)
首先创建自定义整理功能:
int compare_natural(void *data, int len1, const void *str1, int len2, const void *str2) {
if (str1 && len1 > 0 && str2 && len2 > 0) {
NSString *s1 = [[NSString alloc] initWithBytesNoCopy:(void *)str1 length:len1 encoding:NSUTF8StringEncoding freeWhenDone:NO];
NSString *s2 = [[NSString alloc] initWithBytesNoCopy:(void *)str2 length:len2 encoding:NSUTF8StringEncoding freeWhenDone:NO];
// The use of NSNumericSearch is required for your need.
// The others are options depending on your needs
NSComparisonResult res = [s1 compare:s2 options:NSCaseInsensitiveSearch | NSNumericSearch | NSDiacriticInsensitiveSearch];
return res;
} else if (str1 && len1 > 0 && (!str2 || len2 == 0)) {
return -1; // empty strings to the end of the list (optional)
} else if (str2 && len2 > 0 && (!str1 || len1 == 0)) {
return 1; // empty strings to the end of the list (optional)
} else {
return 0;
}
}
然后注册自定义整理器。这需要在打开数据库后完成。
// dbRef is your sqlite3 database reference
int rc = sqlite3_create_collation(dbRef, "BYNUMBER", SQLITE_UTF8, NULL, &compare_natural);
然后更新您的查询,使其以“COLLATE BYNUMBER”
结束选择some_col ORDER BY some_col COLLATE BYNUMBER;