2011-06-08 49 views
0

我的問題是雙重的,外鍵非候選鍵和刪除級聯

  1. 首先,是有可能創造一個外鍵,在MySQL中,從引用表中所引用的表中的列那不是候選人的關鍵?我嘗試使用SQLYOG架構設計器,並奇怪地創建它。只是想與其他人確認,然後假設它可能是sqlyog或mysql實際允許的錯誤。

例如:

表1的列:

SSN:主鍵

名稱:非候選鍵(名字可以重複)

表2列

ID2:主鍵

name_referencing:外鍵在表1名(這是外鍵可能嗎?)

2.如果上述情況是可能的,「ON DELETE CASCADE」發生時會發生什麼。也就是說,如果被引用列的值(在各行中)有相同的值,那麼刪除子元素(在引用中)是否僅在刪除引用表中的最後一個值(重複值)時發生?

+0

我有點困惑你爲什麼問這個問題,似乎你可以通過實驗來回答這個問題,而不用花時間寫出問題。 – derobert 2011-06-08 20:23:40

+0

實際上,在使用sqlyog模式設計器創建它之前,我提出了問題,然後嘗試了第一部分。有點驚訝,如果它是一個SQLYOG的錯誤,甚至是一件事情。雖然沒有嘗試第二部分。 – krishna 2011-06-08 20:40:09

+0

請編輯您的問題,所以我可以收回我的downvote。 – derobert 2011-06-08 20:47:57

回答

1
-- Create the tables 
([email protected]) [test]> create table foo (a int primary key, b int not null, index(b)) engine=innodb; 
Query OK, 0 rows affected (0.33 sec) 

create table bar (b int not null, constraint b_exists foreign key (b) references foo(b) on delete cascade) engine=innodb; 
Query OK, 0 rows affected (0.40 sec) 

因此,MySQL實際上允許這種情況。奇怪的。 Oracle和PostgreSQL不會(都會引發錯誤),我不相信SQL標準允許它(但沒有檢查過,所以可能會出錯)。讓我們看看它是如何處理它的:

-- Fill foo 
([email protected]) [test]> insert into foo values (1,1); 
Query OK, 1 row affected (0.11 sec) 

([email protected]) [test]> insert into foo values (2,1); 
Query OK, 1 row affected (0.07 sec) 

-- Check foreign key works: 
([email protected]) [test]> insert into bar values (1); 
Query OK, 1 row affected (0.13 sec) 

([email protected]) [test]> insert into bar values (2); 
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test`.`bar`, CONSTRAINT `b_exists` FOREIGN KEY (`b`) REFERENCES `foo` (`b`) ON DELETE CASCADE) 

-- Delete 

([email protected]) [test]> delete from foo where a = 1; 
Query OK, 1 row affected (0.09 sec) 

([email protected]) [test]> select * from bar; 
Empty set (0.00 sec) 

因此,MySQL從引用表中刪除行。至少在5.1.49。