Oracle外鍵不加索引會引發死鎖問題

轉載連接:http://www.jb51.net/article/50161.htmsession

這篇文章主要介紹了Oracle外鍵不加索引引發死鎖的狀況及解決,須要的朋友能夠參考下

--建立一個表,此表做爲子表

create table fk_t as select * from user_objects;

delete from fk_t where object_id is null;

commit;

--建立一個表,此表做爲父表

create table pk_t as select * from user_objects;

delete from pk_t where object_id is null;

commit;

--建立父表的主鍵

alter table PK_t add constraint pk_pktable primary key (OBJECT_ID);

--建立子表的外鍵

alter table FK_t add constraint fk_fktable foreign key (OBJECT_ID) references pk_t (OBJECT_ID);

--session1:執行一個刪除操做,這時候在子表和父表上都加了一個Row-S(SX)鎖

delete from fk_t where object_id=100;

delete from pk_t where object_id=100;

--session2:執行另外一個刪除操做,發現這時候第二個刪除語句等待

delete from fk_t where object_id=200;

delete from pk_t where object_id=200;

--回到session1:死鎖立刻發生

delete from pk_t where object_id=100;

session2中報錯:

SQL> delete from pk_table where object_id=200;
delete from pk_table where object_id=200
*
第 1 行出現錯誤:

ORA-00060: 等待資源時檢測到死鎖

當對子表的外鍵列添加索引後,死鎖被消除,由於這時刪除父表記錄不須要對子表加表級鎖。

--爲外鍵創建索引

create index ind_pk_object_id on fk_t(object_id) nologging;

--重複上面的操做session1

delete from fk_t where object_id=100;

delete from pk_t where object_id=100;

--session2

delete from fk_t where object_id=200;

delete from pk_t where object_id=200;

--回到session1不會發生死鎖

delete from pk_t where object_id=100; 
spa



關於外鍵不加索引引發死鎖的詳細分析參考http://blog.csdn.net/robinson1988/article/details/38421991.net


通過驗證,若是外鍵不加索引的確會出現死鎖。所以,外鍵務必添加索引。htm

相關文章
相關標籤/搜索