1

我需要一个级联删除的例子。我的问题是,我在哪里添加它?在我创建 PK 的表中,或者在该 PK 作为 FK 坐在那里的其他表中?

我可以使用“alter table”将“on delete cascade”添加到现有表吗?请举个例子?

@edit MYSQL,使用 phpMyAdmin

@编辑 2

它看起来不错吗?

alter table wplaty
  drop foreign key pesel,
  add constraint pesel foreign key (pesel)
    references baza_osob(pesel) on delete cascade on update restrict;

我的父表 = baza_osob 我的子表 = wplaty

PK 是 pesel,FK 也是 pesel。

@edit3 出现错误:

#1025 - 将 '.\projekt\wplaty' 重命名为 '.\projekt#sql2-1300-6c' 时出错(错误号:152)

4

3 回答 3

3

级联指令进入“子”表,例如

create table parent (
   id int primary key
)

create table child (
   id int primary key
   parent_id int,
   foreign key (parent_id) references parent (id)
      on delete cascade
)

从未尝试对外键进行更改以更改其on设置,但最坏的情况是,您只需删除现有的 FK 并使用新on设置重新定义它。

于 2012-12-17T18:41:21.193 回答
0

您实际上并没有在表上添加“ON DELETE CASCADE”。它是每个外键定义的一部分(或不是)。

于 2012-12-17T18:42:26.797 回答
0

您需要为外键启用此选项。如果您在创建外键时没有添加此选项,那么您应该重新创建它。

alter table <table> drop foreign key <fk name>;

alter table <table> add constraint <fk name> foreign key (<column name>)
  references <ref tble>(<ref column) on delete cascade on update restrict;

在一份声明中:

alter table <table>
  drop foreign key <old fk name>,
  add constraint <new fk name> foreign key (<column name>)
    references <ref tble>(<ref column) on delete cascade on update restrict;
于 2012-12-17T18:51:05.950 回答