如何删除无法连接的行 - SQL Query

时间:2014-09-07 13:04:18

标签: sql objective-c sqlite

我有一个表1,其中包含一些数据,但特别是两列'user'和'date'

我有另一个包含其他数据的表,但也有“user”和“date”列。

正如你已经正确猜到这两个表在“用户”和“日期”上加入。

表1经常被弄乱,数据,添加,编辑,删除等。

我想做的是做一个检查表2的查询,如果有任何行没有加入'user'和'date'的第一表,那么删除该行。

    if (sqlite3_open([dbTable2PathString UTF8String], & Table2DB) == SQLITE_OK)
{
    if (sqlite3_exec(Table2DB, [[NSString stringWithFormat:@"ATTACH DATABASE \'%s\' AS SECOND", [dbTable1PathString UTF8String]] UTF8String], NULL, NULL, &error) == SQLITE_OK)
    {
        NSString* deleteQuery = @"DELETE t2 FROM table2 t2 LEFT JOIN table1 t1 ON t1.user = t2.user AND t1.date = t2.date where t1.user is NULL";

        sqlite3_stmt *deleteStmt;
    if(sqlite3_prepare_v2(Table2DB, [deleteQuery UTF8String], -1, &deleteStmt, NULL) == SQLITE_OK)
    {
        if (SQLITE_DONE != sqlite3_step(deleteStmt))
        {
            NSLog(@"Error while deleting. '%s'", sqlite3_errmsg(Table2DB));
        }
    }
    else
    {
        NSLog(@"Error while creating delete statement. '%s'", sqlite3_errmsg(Table2DB));
    }
    sqlite3_finalize(deleteStmt);
    }
}
else
{
    sqlite3_close(Table2DB); //Even though the open call failed, close the database connection to release all the memory.
}

我之前尝试过这个查询但得到错误

@"DELETE FROM TABLE2 LEFT JOIN TABLE1 ON (TABLE1.user = TABLE2.user AND TABLE1.date= TABLE2.date) where TABLE1.user is 'NULL'"

错误:

near "LEFT": syntax error

我之前尝试过这个查询但得到错误

@"DELETE t2 FROM table2 t2 LEFT JOIN table1 t1 ON t1.user = t2.user AND t1.date = t2.date where t1.user is NULL"

错误:

near "t2": syntax error

1 个答案:

答案 0 :(得分:3)

delete t2
from table2 t2
left join table1 t1 on t1.user = t2.user and t1.date = t2.date
where t1.user is null

基本上你需要left join并删除连接失败的行。