山坳中的SQLite数据库中的一些值:如何通过char和数字键选择sqlite命令?
a1b2
a2b3
a1b10
a10b1
如果在SQL使用order by
这将是:
a10b1
a1b10
a1b2
a2b3
我希望它像objc的NSNumericSearch
这样的:
a1b2
a1b10
a2b3
a10b1
我如何编写SQL语句?
山坳中的SQLite数据库中的一些值:如何通过char和数字键选择sqlite命令?
a1b2
a2b3
a1b10
a10b1
如果在SQL使用order by
这将是:
a10b1
a1b10
a1b2
a2b3
我希望它像objc的NSNumericSearch
这样的:
a1b2
a1b10
a2b3
a10b1
我如何编写SQL语句?
开始通过创建自定义排序功能:
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;
}
}
然后注册自定义排序器。这需要在打开数据库后完成。因此它与 “分页BYNUMBER”
SELECT some_col ORDER BY some_col COLLATE BYNUMBER结束
// dbRef is your sqlite3 database reference int rc = sqlite3_create_collation(dbRef, "BYNUMBER", SQLITE_UTF8, NULL, &compare_natural);
然后更新您的查询;
这很光滑!编写更多的代码,但仍然是一个非常酷的方法。 – StilesCrisis
@StilesCrisis谢谢。好的是它可以重用,如果你有多个查询需要按这种方式排序,那实际上更容易。 – rmaddy
@rmaddy非常感谢你,我已经尝试这种方式,但得到了一个错误'接近'NATURAL':语法错误' – yellow
这不是内置到SQLite中。您需要编写自己的自定义配页器,将其安装到数据库中,并在“按顺序排列”中指定该配页器。 – rmaddy