SQLiteDatabase删除涉及子查询

时间:2012-07-10 14:04:23

标签: java android sql sqlite

我正在使用SQLiteDatabase作为Java库,我需要支持一个非常低版本的Android API(v4),它不附带支持外键的SQLite版本。

因此,为了删除顶级数据及其所有儿童",我需要删除这些孩子,然后以这种方式手动重现与外国人相同的效果关键约束ON DELETE CASCADE

我尝试做的是使用delete api的以下SQL。

DELETE FROM childTable 
WHERE someFK IN (
    SELECT parent_id 
    FROM parentTable 
    WHERE someFlag = 1
)

我提出的初始解决方案是在我的where子句中对select查询进行硬编码,如下所示,但是由于SQLiteDatabase api支持查询,execSQL等,这个解决方案我用得非常错误且使用起来很危险? 解决方法:

String[] whereArgs = {Integer.toString(1)};
this.database.delete(TABLE_CHILD_ONE, COL_ONE_FK_SESSION+" IN (SELECT "+COL_SESSION_ID+" FROM "+TABLE_SESSIONS+" WHERE "+COL_SESSION_DONE+"=?)", whereArgs);
this.database.delete(TABLE_CHILD_TWO, COL_TWO_FK_SESSION+" IN (SELECT "+COL_SESSION_ID+" FROM "+TABLE_SESSIONS+" WHERE "+COL_SESSION_DONE+"=?)", whereArgs);
this.database.delete(TABLE_CHILD_THREE, COL_THREE_FK_SESSION+" IN (SELECT "+COL_SESSION_ID+" FROM "+TABLE_SESSIONS+" WHERE "+COL_SESSION_DONE+"=?)", whereArgs);

1 个答案:

答案 0 :(得分:1)

您可以为每个表创建触发器:

CREATE TRIGGER delete_cascade AFTER DELETE ON parentTable
BEGIN
    DELETE FROM childTable child WHERE child.parent_id=OLD.id;
END;

在交易中运行。

More about triggers