mardi 2 juin 2015

SQLite INNER JOIN WHERE column not null

I'm trying to get this SQL query correct but I keep getting a single row with null values.

So I got two tables.

Table A is chat table.

Table B is wallpaper table.

chat may or may not have any wallpaper ID assigned to is foreign key.

I'm trying to get the wallpaper attached to a chat using the following query:

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)";

inside my method:

-(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;
}

But that keeps returning me a single wallpaper entity with all fields NULL.

A chat can only have 1 wallpaper. So I only want to fetch a single wallpaper where it is linked to a chat based identified by the chatHeaderID.

As far as I can see, the SQL query found the matching chat entry from the chat table based on the chatHeaderID I passed in but it seems to be ignoring my WHERE clause:

(chat.id_chat = ? AND chat.id_wallpaper NOT NULL)

What I was expecting to see is the SQL query returning 0 entries at the moment because I have not linked any wallpaper entries with any chat entries.

Any ideas ? :D

Aucun commentaire:

Enregistrer un commentaire