MySQL級聯操作

2021-10-23 05:53:34 字數 1256 閱讀 5286

當有了外來鍵約束的時候,必須先修改或刪除副表中的所有關聯資料,才能修改或刪除主表!但是,我們希望直接修改或刪除主表資料,從而影響副表資料。可以使用級聯操作實現

示例:

建立乙個主表(部門表)和從表(員工表)

//主表

create table dept(id int primary key auto_increment,

`name` varchar(50));

//從表

create table emp(id int primary key auto_increment,

`name` varchar(50) not null unique,

did int,

foreign key(did) references dept(id)

)

新增幾條資料

insert into dept values(null,'a');

insert into dept values(null,'b');

insert into emp values(null,'zs',2);

insert into emp values(null,'ls',1);

insert into emp values(null,'ww',2);

dept表:

emp表:

如果沒有級聯是 刪除 或 更新 不了dept部門表中的資料的,可以試一下

delete from dept where id=2;
關聯刪除

alter table emp add foreign key(did) references dept(id) on delete cascade
關聯刪除後再刪除dept部門表的資料

delete from dept where id=2;
dept表:

emp表:

刪除成功,主表刪除資料後,從表對應的資料也刪除了

MySQL沒有級聯 MySql級聯操作

外來鍵約束對子表的含義 如果在父表中找不到候選鍵,則不允許在子表上進行insert update 外來鍵約束對父表的含義 在父表上進行update delete以更新或刪除在子表中有一條或多條對應匹配行的候選鍵時,父表的行為取決於 在定義子表的外來鍵時指定的on update on delete子句...

mysql的級聯操作 mysql的級聯操作

1.建立表a create table a name char 20 not null,id char 20 not null primary key 2.建立表b create table b b name char 20 not null,b id char 20 not null constr...

mysql 級聯更新和刪除操作

我們通常有這樣的需求 刪除表table 1中記錄,需要同時刪除其它表中與table 1有關的若干記錄。對於這種,我們有兩種解決方法 一,使用innodb表的外來鍵約束 alter table score add constraint student ibfk1 foreign key sid sid...