0

我有以下 SQL 语句:

const char* sqlStatement = "SELECT ((? - deal.latitude) * (? - deal.latitude) + (? - deal.longitude) * (? - deal.longitude)) AS distance, id, title, shop, latitude, longitude FROM deal WHERE (type = ?) AND category IN (?) AND tribe IN (?) ORDER BY distance LIMIT 20;";

// ...

sqlite3_bind_double(preparedStatement, 1, location.latitude);
sqlite3_bind_double(preparedStatement, 2, location.latitude);
sqlite3_bind_double(preparedStatement, 3, location.longitude);
sqlite3_bind_double(preparedStatement, 4, location.longitude);
sqlite3_bind_int(preparedStatement, 5, type);
sqlite3_bind_text(preparedStatement, 6, [categories UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(preparedStatement, 7, [tribes UTF8String], -1, SQLITE_TRANSIENT);

在这里,第六个和第七个参数导致查询失败,我的意思是我里面的块

while (sqlite3_step(preparedStatement) == SQLITE_ROW) {

不被执行。类别和部落的构建如下:

NSArray* userCategories = [CategoryDataController getUserCategories];
NSMutableString* categories = [[NSMutableString alloc] init];

for (NSNumber *category in userCategories) {
    [categories appendString:[[NSString alloc] initWithFormat:@"%@, ", category]];
}
if ([categories length] > 0) {
    categories = (NSMutableString *)[categories substringToIndex:[categories length] - 2];
}

NSArray* userTribes = [TribeDataController getUserTribes];
NSMutableString* tribes = [[NSMutableString alloc] init];

for (NSNumber* tribe in userTribes) {
    [tribes appendString:[[NSString alloc] initWithFormat:@"%@, ", tribe]];
}
if ([tribes length] > 0)
    tribes = (NSMutableString *)[tribes substringToIndex:[tribes length] - 2];

userCategories 和 userTribes 是 NSNumber 的数组,如果我记录部落和类别,我会得到格式良好的字符串,类似于:

1, 2, 3, 4, 5

奇怪的是,我使用 sqlite3_bind_ 函数来构建查询,如下所示:

NSString *sqlStatementNSString = [[NSString alloc] initWithFormat:@"SELECT ((%f - deal.latitude) * (%f - deal.latitude) + (%f - deal.longitude) * (%f - deal.longitude)) AS distance, id, title, shop, latitude, longitude FROM deal WHERE type = %d AND category IN (%@) AND tribe IN (%@) ORDER BY distance LIMIT 20;", location.latitude, location.latitude, location.longitude, location.longitude, type, categories, tribes];
const char *sqlStatement = [sqlStatementNSString UTF8String];

有用!我做错了什么?事先谢谢(请原谅我的英语)。

4

1 回答 1

0

我也已经搜索过这个问题的答案,而且似乎准备好的语句通常不支持 IN 运算符。您可以在此站点上找到各种解决方案。我的首选解决方案(从其中一个答案中获得)是在 IN 运算符列表中准备一个具有固定数量槽的语句:

SELECT * FROM db WHERE id IN (?, ?, ?, ?, ?, ?)

然后执行查询 ((n + 5) / 6) 次(在本例中)并合并所有答案。如果您的槽数少于槽数,则用 NULL 填充其余部分,或复制最后一个条目。希望优化器应该避免重复比较。

重用准备好的语句可能比构建和运行自定义查询字符串更快(但可以肯定的是配置文件!)

于 2012-05-15T18:40:47.263 回答