資料庫級聯更新和刪除

2021-09-30 16:00:40 字數 1639 閱讀 6136

如果a(id,name)表為主表。

b(id, a_id, name)表為從表,b.a_id外來鍵關聯到a_id。

那麼如果需要更新a.id或者刪除a的資料,且在b表中有資料關聯到需要更新或者刪除的a表紀錄,那麼普通的更新必然會有外來鍵衝突。

解決方法如下:

mysql

在b表中建立delete cascade, update cascade.

user表:

create table user

( userid integer not null auto_increment primary key,

username varchar(12) not null

) type=innodb;

password表:

create table password

( userid integer not null,

password varchar(12) not null,

index (userid),

foreign key (userid) references user (userid)

on delete cascade

on update cascade

) type=innodb;

1、mysql支援外來鍵約束,並提供與其它db相同的功能,但表型別必須為 innodb

2、建外鍵的表的那個列要加上index.

oracle

在b表中建立delete cascade.

關於級聯更新需要新增trigger,當更新a.id的同時更新b.a_id.

trigger:

create or replace trigger a_id_update after update on venue for each row

begin

if :new.id != :old.id then

update b set a_id=:new.id where a_id=:old.id;

end if;

end;

此種tirgger只能解決更新單條a記錄的更新。

sql 10g>select * from a;    id

---------- 1

2 3sql 10g>select * from b;

a_id

---------- 1

2 3>update a set id=id+1;

錯誤結果

sql 10g>select *from a;p1

---------- 2

3 4sql 10g>select * from b; f1

---------- 4

4 4參考:

可以看到f表的記錄變成 了三4,顯然這不是我們想要的結果,單父表這邊把1更新成2,子表也相應把1變成2,這時候子表就有2個2了,然後父表把2更新成3,子表更新兩個2成 3,這時候子表就有三個3了,當父表把3更新成4,子表會把三個3都更新成4,也就是最後我們看到的結果,這顯然是不符合需求的。我們除了限制父表的多條 記錄更新外還有什麼辦法呢?

SQL級聯更新和級聯刪除

alter table 表名 add constraint 約束名 foreign key 欄位名 references 主表名 欄位名 on delete cascade 語法 foreign key column n references referenced table name ref co...

資料庫的更新和刪除

using system using system.collections.generic using system.linq using system.text using system.threading.tasks using mysql.data.mysqlclient namespace ...

mysql 級聯更新和刪除操作

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