自动删除联结数据以及记录的DELETE?

时间:2013-04-21 01:03:49

标签: mysql sql foreign-keys foreign-key-relationship junction-table

我有用户,有优惠和联结表users_offers。

我是否可以使用外键关系进行设置,以确保在删除任何用户或优惠时自动删除联结数据?

2 个答案:

答案 0 :(得分:1)

您可以在模型创建中指定:

CREATE TABLE users_offers (user_id INT NOT NULL,
                           offer_id INT NOT NULL,
                           PRIMARY KEY (user_id, offer_id),
                           FOREIGN KEY (user_id) REFERENCES users(id)
                               ON DELETE CASCADE,
                           FOREIGN KEY (offer_id) REFERENCES offers(id)
                               ON DELETE CASCADE);

您可以在this Fiddle中看到一个有效的例子。

答案 1 :(得分:1)

声明参照动作:ON DELETE CASCADE,例如:

CREATE TABLE user (
    user_id int PRIMARY KEY
);

CREATE TABLE offer (
    offer_id int PRIMARY KEY
);

CREATE TABLE user_offer (
    user_id int,
    offer_id int,
    PRIMARY KEY (user_id, offer_id),
    FOREIGN KEY (user_id) REFERENCES user (user_id) ON DELETE CASCADE,
    FOREIGN KEY (user_id) REFERENCES offer (offer_id) ON DELETE CASCADE
);

[SQL Fiddle]

有趣的是,似乎在“速记”外键语法中指定引用操作不起作用(在MySQL 5.5.30,5.6.6 m9下确认)。解析了以下内容,但删除user后,相应的user_offer不会被删除:

CREATE TABLE user_offer (
    user_id int REFERENCES user (user_id) ON DELETE CASCADE,
    offer_id int REFERENCES offer (offer_id) ON DELETE CASCADE,
    PRIMARY KEY (user_id, offer_id)
);