问题
I needed an example of cascade delete. My question is, where do I add it? In the table I create PK, or in other tables where this PK is sitting there as FK?
Can I use "alter table" to add "on delete cascade" to existing table? An example please?
@edit MYSQL, using phpMyAdmin
@edit 2
Does it look good?
alter table wplaty
drop foreign key pesel,
add constraint pesel foreign key (pesel)
references baza_osob(pesel) on delete cascade on update restrict;
My parent table = baza_osob My child table = wplaty
PK is pesel, FK is pesel as well.
@edit3 Got error:
#1025 - Error on rename of '.\projekt\wplaty' to '.\projekt#sql2-1300-6c' (errno: 152)
回答1:
cascade directives go into the "child" tables, e.g.
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
)
Never tried doing an alter on a foreign key to change its on
settings, but worst case, you simply drop the existing FK and redefine it with the new on
settings in place.
回答2:
You actually don't add the 'ON DELETE CASCADE' on a table. It's part (or not) of each Foreign Key definition.
回答3:
You need to enable this option for the foreign key. If you did not add this option when you created foreign key, then you should recreate it.
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;
In one statement:
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;
来源:https://stackoverflow.com/questions/13920078/on-delete-cascade-where-i-have-to-add-it