通过使用单个语句执行多个查询来获取最大值

时间:2013-02-06 08:27:55

标签: iphone objective-c sqlite

我是iphone开发的新手。我有一个SQL查询“从test中选择pubdate,其中rowid in(从test中选择max(rowid))”。当我执行此查询时,我没有得到适当的结果。 源代码:

NSString *query=[NSString stringWithFormat:@"select pubdate from %@ where rowid in(select max(rowid) from %@)",tableName,tableName];
const char *  sql = [query UTF8String];
sqlite3_stmt *lastInsVal_statement = nil;
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString * docsDir = [paths objectAtIndex:0];
NSString * thePath = [docsDir stringByAppendingPathComponent:
                      @"Training_Project2.sqlite"];
sqlite3_open([thePath UTF8String], &database);
sqlite3_prepare_v2(database, sql, -1, &lastInsVal_statement, NULL);
NSString* pubdate;
while(sqlite3_step(lastInsVal_statement)==SQLITE_ROW){
    const char* str = (const char*)sqlite3_column_text(lastInsVal_statement, 2);
    pubdate = [NSString stringWithCString:str encoding:NSUTF8StringEncoding];
}
sqlite3_finalize(lastInsVal_statement);
sqlite3_close(database);
return pubdate;

1 个答案:

答案 0 :(得分:0)

这一行:

const char* str = (const char*)sqlite3_column_text(lastInsVal_statement, 2);

应更改为此行:

const char *str = (const char *)sqlite3_column_text(lastInsVal_statement, 0);

0表示您希望获得在查询中选择的第一列!