为什么我的外键不工作?

时间:2016-05-10 02:17:15

标签: java android sqlite foreign-keys

我的创建表语句:

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_table)级联并删除那些通过外键链接的记录。

我也有这个代码:

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

我误解了这些是如何工作的?这不是外键的用途吗?为什么它没有级联?

1 个答案:

答案 0 :(得分:0)

如果您想要任何级联

,则必须明确提及

更改下面的查询

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));