简体   繁体   English

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

[英]Why aren't my foreign keys working?

My create table statement: 我的创建表语句:

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

However now if I do something like 但是现在如果我做类似的事情

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

Which is basically DELETE FROM ACCOUNTS WHERE _ID = some_id but it isn't cascading through the other tables (employees or main_table) and deleting any records there that link up through the foreign keys. 基本上,这是DELETE FROM ACCOUNTS WHERE _ID = some_id但是它并没有级联其他表(员工或main_table),并且不会删除通过外键链接的任何记录。

I do have this code as well: 我也有以下代码:

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

Am I misunderstanding how these work? 我是否误解了这些工作原理? Isn't this what foreign keys are for? 这不是外键的作用吗? Why isn't it cascading? 为什么它不是级联的?

You have to mention explicitly if you want any cascading 如果需要级联,则必须明确提及

Change the query like below 如下更改查询

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM