我试图让这个SQL查询正确但我不断获得一个空值的行。
所以我有两张桌子。
表A是chat
表。
表B是wallpaper
表。
chat
可能或可能不会分配任何壁纸ID是外键。
我尝试使用以下查询将壁纸附加到聊天中:
const char *query = "SELECT wallpaper.* FROM wallpaper INNER JOIN chat ON wallpaper.id_wallpaper = chat.id_wallpaper AND (chat.id_chat = ? AND chat.id_wallpaper NOT NULL)";
在我的方法中:
-(Wallpaper *)getWallpaperForChatHeaderID:(NSString *)chatHeaderID
{
sqlite3_stmt *statement;
const char *query = "SELECT wallpaper.* FROM wallpaper INNER JOIN chat ON wallpaper.id_wallpaper = chat.id_wallpaper AND (chat.id_chat = ? AND chat.id_wallpaper NOT NULL)";
Wallpaper *wallpaper = nil;
if(sqlite3_prepare_v2(_database, query, -1, &statement, nil) == SQLITE_OK)
{
sqlite3_bind_int(statement, 1, [chatHeaderID intValue]);
int statusCode = sqlite3_step(statement);
if(statusCode == SQLITE_DONE)
{
long idWallpaper = sqlite3_column_int(statement, 0);
char *dbFilename = (char *)sqlite3_column_text(statement, 1);
...
wallpaper = [[Wallpaper alloc] initWithWallpaperID:idWallpaper ....];
}
else
{
NSLog(@"sql step status error code: %d", statusCode);
}
sqlite3_finalize(statement);
}
else
{
NSLog(@"Failed to get wallpaper for chat header with ID: %@", chatHeaderID);
}
return wallpaper;
}
但是这会让我返回一个wallpaper
个实体,所有字段都为NULL。
聊天只能有1个壁纸。所以我只想获取一个wallpaper
,它链接到chatHeaderID标识的聊天。
据我所知,SQL查询根据我传入的chat
在chat
表中找到了匹配的chatHeaderID
条目,但似乎忽略了我的WHERE子句:
(chat.id_chat = ? AND chat.id_wallpaper NOT NULL)
我期待看到的是SQL查询此刻返回0个条目,因为我没有将任何壁纸条目与任何聊天条目链接。
有什么想法吗? :d
答案 0 :(得分:0)
我的另一个问题是我自己解决了= /
不确定为什么上面的问题代码不起作用,但我发现了一项似乎可以产生预期结果的工作。
-(Wallpaper *)getWallpaperForChatHeaderID:(NSString *)chatHeaderID
{
sqlite3_stmt *statement;
const char *query = "SELECT wallpaper.* FROM wallpaper INNER JOIN chat ON wallpaper.id_wallpaper = chat.id_wallpaper WHERE chat.id_chat = ? AND chat.id_wallpaper NOT NULL";
Wallpaper *wallpaper = nil;
if(sqlite3_prepare_v2(_database, query, -1, &statement, nil) == SQLITE_OK)
{
sqlite3_bind_int(statement, 1, [chatHeaderID intValue]);
while (sqlite3_step(statement) == SQLITE_ROW)
{
long idWallpaper = sqlite3_column_int(statement, 0);
...
wallpaper = [[Wallpaper alloc] initWithWallpaperID:idWallpaper ...];
}
sqlite3_finalize(statement);
}
else
{
NSLog(@"Failed to get wallpaper for chat header with ID: %@", chatHeaderID);
}
return wallpaper;
}
这里的不同之处在于我使用:
while(... == SQLITE_ROW)
{
...
}
检查是否满足WHERE过滤条件的匹配行的条件:)
我想指出我已将上述SQL查询更改为使用:
SELECT wallpaper.* FROM wallpaper INNER JOIN chat ON wallpaper.id_wallpaper = chat.id_wallpaper WHERE chat.id_chat = ? AND chat.id_wallpaper NOT NULL
但我已经测试过:
SELECT wallpaper.* FROM wallpaper INNER JOIN chat ON wallpaper.id_wallpaper = chat.id_wallpaper AND (chat.id_chat = ? AND chat.id_wallpaper NOT NULL)
两者似乎都有效。
我会使用包含明确WHERE
关键字的关键字,因为它看起来更具可读性。