How do I delete all items from one table that don't have any members of another table that point to them?

StackOverflow https://stackoverflow.com/questions/21072333

  •  27-09-2022
  •  | 
  •  

Question

The table is created like this: (in python)

cursor.execute("CREATE TABLE Story (dbId INTEGER PRIMARY KEY, title TEXT, quickCode TEXT, gradeLevel TEXT, folder TEXT, expository INTEGER)")
cursor.execute("CREATE TABLE Question (dbId INTEGER PRIMARY KEY, storyId INTEGER, questionOrder INTEGER, body TEXT, answer TEXT, factual INTEGER)")
cursor.execute("CREATE TABLE Paragraph (dbId INTEGER PRIMARY KEY, storyId INTEGER, body TEXT, generalization INTEGER)")

The database is copied in my app, and a Reading table added like this:

static NSString *dbIdColumn         = @"dbId";
static NSString *startTimeColumn    = @"startTime";
static NSString *sessionIdColumn    = @"sessionId";
static NSString *elapsedTimeColumn  = @"elapsedTime";
static NSString *totalWordsColumn   = @"totalWords";
static NSString *markedItemsColumn  = @"markedItems";
static NSString *readingOrderColumn = @"readingOrder";
@implementation ReadingController

+ (NSString *)creationString {
    return [NSString stringWithFormat:@"CREATE TABLE Reading (%@ %@, %@ %@, %@ %@, %@ %@, %@ %@, %@ %@, %@ %@)",
            dbIdColumn, SQL_DB_ID_TYPE,
            startTimeColumn, SQL_DATE_TYPE,
            sessionIdColumn, SQL_INTEGER_TYPE,
            elapsedTimeColumn, SQL_DOUBLE_TYPE,
            totalWordsColumn, SQL_INTEGER_TYPE,
            markedItemsColumn, SQL_INTEGER_TYPE,
            readingOrderColumn, SQL_INTEGER_TYPE
            ];
}

then add sessions, and usually Readings as part of those sessions, but sometimes no readings are created.

I am trying to delete the unused sessions (those with no readings) on an iOS device

+ (void)removeUnusedSessions {
    [[[DatabaseController singleton]queue]inDatabase:^(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"DELETE FROM Session where NOT EXISTS (SELECT NULL FROM Reading.sessionId = Session.dbId)"];
        [db executeUpdate:sql];
        if (![db hadError]) {
            NSLog(@"Removed unused Sessions");
        } else {
            NSError *error = [db lastError];
            NSLog(@"Unable to remove unused sessions: %@", [error description]);
        }
    }];
}

I get an error code like this:

$0 = 0x11453bf0 Error Domain=FMDatabase Code=1 "near "=": syntax error" UserInfo=0x11444fd0 {NSLocalizedDescription=near "=": syntax error}

Any ideas why this is not working? Any input on a better approach?

Was it helpful?

Solution

The subquery must be a syntactically valid query; the table name and WHERE were missing:

DELETE FROM Session
WHERE NOT EXISTS (SELECT NULL
                  FROM Reading
                  WHERE Reading.sessionId = Session.dbId)

This query can be simplified to:

DELETE FROM Session
WHERE dbId NOT IN (SELECT sessionId
                   FROM Reading)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top