2

我将 SQLiteDatabase 用于 Java 库,并且我需要支持非常低版本的 Android API (v4),它不附带支持外键的 SQLite 版本。

因此,为了删除顶级数据及其所有“子项”,我需要先删除这些子项,以便手动重现与外键约束相同的效果ON DELETE CASCADE

我正在尝试做的是带有删除 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);
4

1 回答 1

1

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

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

在事务中运行它。

更多关于触发器

于 2012-07-10T17:51:49.277 回答