在FMDatabase for iOS中使用LIKE“%something%”

时间:2012-03-09 21:02:35

标签: iphone fmdb

我不确定这是否属实,但我被告知FMDatabase如果你这样做会表现更好

NSString *query = [NSString stringWithFormat:@"SELECT * FROM db where col=?"];
FMResultSet *rs = [theDatabase executeQuery:query, columnToLookFor];

vs

NSString *query = [NSString stringWithFormat:@"SELECT * FROM db where col='columnToLookFor'"];
FMResultSet *rs = [theDataBase executeQuery:query];

所以我们有一个搜索查询来执行此操作:

NSString *query = [NSString stringWithFormat:@"SELECT Symbol, Category FROM Symbols where Category like \"%%%@%%\" or Symbol like \"%%%@%%\" group by Symbol, Category order by Category", searchtext, searchtext];
FMResultSet *rs = [theDatabase executeQuery:query];

我正在尝试将其更改为:

NSString *query = [NSString stringWithFormat:@"SELECT Symbol, Category FROM Symbols where Category like \"%%?%%\" or Symbol like \"%%?%%\" group by Symbol, Category order by Category"];
FMResultSet *rs = [theDatabase executeQuery:query, searchtext, searchtext];

然而在带有?的第二种形式中,我的FMResultSet为0,我不确定在这种情况下我做错了什么。这会加速我们的搜索吗?或者这个功能花费这么长时间的数据库设计更糟糕。

2 个答案:

答案 0 :(得分:0)

假设你的第一个中的searchtext变量是一个问号,那么没有理由为什么一个会工作而另一个不起作用,因为你把这个文字放在第二个的SQL字符串中。您可能希望将两行更改为:

NSString *query = [NSString stringWithString:@"SELECT Symbol, Category FROM Symbols where Category like '%%?%%' or Symbol like '%%?%%' group by Symbol, Category order by Category"];
FMResultSet *rs = [theDatabase executeQuery:query];

此外,我会在行之前执行此操作,以查看在FMDB处理SQL时的样子:

[theDatabase setTraceExecution:YES];

编辑:尝试将其更改为此并查看跟踪执行的内容:

NSString *query = [NSString stringWithString:@"SELECT Symbol, Category FROM Symbols where Category like '%%?%%' or Symbol like '%%?%%' group by Symbol, Category order by Category"];
FMResultSet *rs = [theDatabase executeQuery:query, searchtext, searchtext, nil];

答案 1 :(得分:-1)

FMResultSet *result = [db executeQuery: @"SELECT * FROM channels_list WHERE type = 'person' AND members LIKE (?)",[NSString stringWithFormat:@"%%%@%%", userID]];