複製鏈接
請複製以下鏈接發送給好友

級聯刪除

鎖定
外鍵的級聯刪除:如果父表中的記錄被刪除,則子表中對應的記錄自動被刪除
父表——被外鍵引用的表
子表——引用父表中的鍵作為外鍵的表
中文名
級聯刪除
外文名
Foreign Keys with Cascade Delete
解    釋
其外鍵值引用刪除主鍵值所有行
語    種
Foreign Key
註    釋
ref_name:外鍵要參考的表主鍵列

目錄

級聯刪除解釋

父表中刪除包含主鍵值的行的操作,該值由子表的現有行中的外鍵列引用。在級聯刪除中,刪除父表中的記錄時,同時刪除子表中外鍵引用此主鍵的記錄。
例:
employee 表中有員工的dept_id 引用department表中dept_id( 同時為department主鍵 )作為外鍵,當department表(父表)中一個部門被刪除,employee表(子表)中引用這個部門的dept_id作為dept_id的記錄也自動被刪除。 [1] 

級聯刪除語法

Foreign Key
(column[,...n])
references referenced_table_name[(ref_column[,...n])]
[on delete cascade]
[on update cascade]

級聯刪除註釋

column:列名
referenced_table_name:外鍵參考的主鍵表名稱
ref_name:外鍵要參考的表的主鍵列
on delete:刪除級聯
on update:更新級聯
SQL級聯刪除——刪除主表同時刪除從表——同時刪除具有主外鍵關係的表
create table a
(
id varchar(20) primary key,
password varchar(20) not null
)
create table b
(
id int identity(1,1) primary key,
name varchar(50) not null,
userId varchar(20),
foreign key (userId) references a(id) on delete cascade
)
表B創建了外碼userId 對應A的主碼ID,聲明瞭級聯刪除

級聯刪除測試數據

insert a values ('11','aaa')
insert a values('23','aaa')
insert b values('da','11')
insert b values('das','11')
insert b values('ww','23')
刪除A表內id為‘11’的數據,發現B表內userId 為“11”也被數據庫自動刪除了,這就是級聯刪除
delete a where id='11'
參考資料