为什么我的外键不起作用?

50few1ms  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(428)

我的create table语句:

CREATE TABLE main_table (
    _ID INTEGER PRIMARY KEY AUTOINCREMENT, 
    account_id INTEGER NOT NULL, 
    employee_id INTEGER NOT NULL,
    rating REAL NOT NULL, 
    timestamp LONG NOT NULL, 
    FOREIGN KEY(account_id) REFERENCES ACCOUNTS(_ID), 
    FOREIGN KEY(employee_id) REFERENCES EMPLOYEES(_ID), 
    UNIQUE (account_id, employee_id, timestamp));

但是现在如果我做了

public void deleteAccount(long accountId) {
    mDatabase.delete(
            ACCOUNTS, 
            _ID + " = ?", 
            new String[]{accountId + ""}
    );
}

基本上是 DELETE FROM ACCOUNTS WHERE _ID = some_id 但它不会通过其他表(employees或main表)级联并删除通过外键链接的任何记录。
我也有这个代码:

@Override
public void onConfigure(SQLiteDatabase db){
    db.setForeignKeyConstraintsEnabled(true);
}

我是不是误解了它们是怎么工作的?这不是外键的用途吗?为什么不是层叠的?

p4rjhz4m

p4rjhz4m1#

如果您想要任何级联,您必须明确地提到
如下所示更改查询

CREATE TABLE main_table (
    _ID INTEGER PRIMARY KEY AUTOINCREMENT, 
    account_id INTEGER NOT NULL, 
    employee_id INTEGER NOT NULL,
    rating REAL NOT NULL, 
    timestamp LONG NOT NULL, 
    FOREIGN KEY(account_id) REFERENCES ACCOUNTS(_ID) ON DELETE CASCADE,
    FOREIGN KEY(employee_id) REFERENCES EMPLOYEES(_ID) ON DELETE CASCADE,
    UNIQUE (account_id, employee_id, timestamp));

相关问题