我有用户,有要约和联结表users_offers。

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

最佳答案

声明一个引用动作: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)
);

关于mysql - 自动删除联结数据以及记录的DELETE?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16126945/

10-14 15:16