[英]CASCADE behaviour on the drop of a foreign key
我不清楚當刪除“外鍵約束”時指定選項CASCADE會發生什么。
例如,考慮這個命令
ALTER TABLE table1 DROP CONSTRAINT foreignKeyToTable2 CASCADE.
在這種情況下CASCADE應該做什么選擇? 如果省略它會怎么樣? 如果我寫RESTRICT而不是CASCADE?
注意:這個查詢示例摘自“Ramez Elmasri,Shamkant B. Navathe - 數據庫系統基礎,第5章末尾”。
只有在刪除主鍵時才需要刪除約束的cascade
選項,而不是在刪除外鍵時。
在Postgres中考慮這個例子:
create table t1 (id integer, constraint pk_one primary key (id));
create table t2 (id integer primary key, id1 integer references t1);
當您嘗試運行時:
alter table t1 drop constraint pk_one;
你得到:
ERROR: cannot drop constraint pk_one on table t1 because other objects depend on it
Detail: constraint t2_id1_fkey on table t2 depends on index pk_one
Hint: Use DROP ... CASCADE to drop the dependent objects too.
如果您運行:
alter table t1 drop constraint pk_one cascade;
你得到:
NOTICE: drop cascades to constraint t2_id1_fkey on table t2
告訴你,還需要刪除需要主鍵的外鍵。
請注意,並非所有DBMS都支持級聯丟棄。 Postgres和Oracle做。
MySQL,SQL Server或Firebird沒有。 您需要在這些DBMS中手動刪除外鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.