繁体   English   中英

非候选键的外键和删除级联

[英]foreign key to non candidate key and on delete cascade

我的问题是两个方面,

  1. 首先,是否可以在 mysql 中创建一个外键,从引用表到被引用表中不是候选键的列? 我使用 SQLYOG 模式设计器进行了尝试,它奇怪地创建了它。 只是想与其他人确认,然后假设它是一个错误,可能是 sqlyog 或 mysql 实际上允许它。

例子:

表 1 列:

ssn:主键

名称:非候选键(名称可以重复)

表2列

id2:主键

name_reference:table1 中名称的外键(这个外键可能吗??)

2.如果上述情况是可能的,当'on delete cascade'发生时会发生什么。 也就是说,如果引用的列有相同的值(在不同的行中),子项(在引用中)的删除是否仅在引用表中的最后一个值(重复值)的删除时发生?

-- 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 中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM