删除包含外键的数据

Delete data that contains foreign key

我通常使用外键来获得良好实践并保持数据完整性,但在尝试删除某些数据时我总是遇到以下“问题”:

我有一个主要组 table 的场景:

我还有其他几个与群组相关的 table,例如:

user_group(用户和组之间的关系table)

course_group(课程和组之间的关系table)

删除组时,我总是需要删除之前相关 table 中对该组的引用...但目前我有几个关系 table,我的排除代码结束了越来越大了。

My question is: is there any function or library that I could use so that this work could be done more automatically? A function that may check for me all these references and already exclude. If anyone has any idea how to make it faster and with the smallest possible number of code thanks. Note: I am currently working with PHP

您希望 on delete cascade 作为 children table 中外键约束的一个选项。

假设 table groups 看起来像:

create table groups (
    id int primary key,
    ... -- other columns here
);

然后您可以将 child table user_groups 声明为:

create table user_groups (
    ... -- some columns here
    group_id int,
    foreign key (group_id) references groups(id) on delete cascade
)