-- 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。
我有點困惑你爲什麼問這個問題,似乎你可以通過實驗來回答這個問題,而不用花時間寫出問題。 – derobert 2011-06-08 20:23:40
實際上,在使用sqlyog模式設計器創建它之前,我提出了問題,然後嘗試了第一部分。有點驚訝,如果它是一個SQLYOG的錯誤,甚至是一件事情。雖然沒有嘗試第二部分。 – krishna 2011-06-08 20:40:09
請編輯您的問題,所以我可以收回我的downvote。 – derobert 2011-06-08 20:47:57