删除外键时的 CASCADE 行为

Nis*_*sba 2 sql cascade foreign-keys alter-table

我不清楚当删除指定选项 CASCADE 的“外键约束”时会发生什么。

例如,考虑这个命令

ALTER TABLE table1 DROP CONSTRAINT foreignKeyToTable2 CASCADE.
Run Code Online (Sandbox Code Playgroud)

在这种情况下,选项 CASCADE 应该做什么?如果我省略它会发生什么?如果我写 RESTRICT 而不是 CASCADE 呢?

注意:此查询示例摘自“Ramez Elmasri,Shamkant B. Navathe - 数据库系统基础知识,第 5 章末尾”。

小智 6

仅在删除主cascade键时才需要删除约束的选项,而在删除外键时则不需要。

考虑 Postgres 中的这个例子:

create table t1 (id integer, constraint pk_one primary key (id));
create table t2 (id integer primary key, id1 integer references t1);
Run Code Online (Sandbox Code Playgroud)

当您尝试运行时:

alter table t1 drop constraint pk_one;
Run Code Online (Sandbox Code Playgroud)

你得到:

create table t1 (id integer, constraint pk_one primary key (id));
create table t2 (id integer primary key, id1 integer references t1);
Run Code Online (Sandbox Code Playgroud)

如果你运行:

alter table t1 drop constraint pk_one cascade;
Run Code Online (Sandbox Code Playgroud)

你得到:

alter table t1 drop constraint pk_one;
Run Code Online (Sandbox Code Playgroud)

告诉您需要主键的外键也被删除了。


请注意,并非所有 DBMS 都支持级联删除。Postgres 和 Oracle 都这样做。
MySQL、SQL Server 或 Firebird 没有。您需要在这些 DBMS 中手动删除外键。