删除级联上的外键约束不起作用postgres

时间:2017-09-07 21:09:41

标签: sql postgresql

当我运行DELETE FROM users WHERE id='some_id'时,beta_keys表上的记录不会被删除。

beta_keys表:

CREATE TABLE beta_keys (
    id serial PRIMARY KEY,
    key VARCHAR(60) UNIQUE NOT NULL,
    created_at TIMESTAMP NOT NULL,
    updated_at TIMESTAMP
);

用户表:

CREATE TABLE users (
    id serial PRIMARY KEY,
    email VARCHAR (256) UNIQUE NOT NULL,
    password VARCHAR (60) NOT NULL,
    beta_key_id INTEGER,
    created_at TIMESTAMP NOT NULL,
    updated_at TIMESTAMP,
    CONSTRAINT users_beta_key_id_fkey FOREIGN KEY (beta_key_id)
        REFERENCES beta_keys (id) MATCH SIMPLE
        ON DELETE CASCADE
);

1 个答案:

答案 0 :(得分:3)

users引用beta_keysdelete cascade通过在删除引用的行(users)时删除引用行(beta_keys)来工作。

sqlfiddle:http://sqlfiddle.com/#!17/a7495/1