我的问题有两个,
示例:
table1列:
ssn:主键
名称:非候选键(名称可以重复)
table2列
id2:主键
name_referencing:table1中名称的外键(可能是这个外键吗?)
2.如果上述情况可能,当“删除级联”发生时会发生什么。也就是说,如果引用列中存在相同的值(在各行中),那么删除子项(在引用中)是否仅在删除引用表中的最后一个值(重复值)时发生?
答案 0 :(得分:1)
-- Create the tables
(anthony@localhost) [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
(anthony@localhost) [test]> insert into foo values (1,1);
Query OK, 1 row affected (0.11 sec)
(anthony@localhost) [test]> insert into foo values (2,1);
Query OK, 1 row affected (0.07 sec)
-- Check foreign key works:
(anthony@localhost) [test]> insert into bar values (1);
Query OK, 1 row affected (0.13 sec)
(anthony@localhost) [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
(anthony@localhost) [test]> delete from foo where a = 1;
Query OK, 1 row affected (0.09 sec)
(anthony@localhost) [test]> select * from bar;
Empty set (0.00 sec)
因此,MySQL会从引用表中删除该行。至少在5.1.49。