Reputation: 3647
My question is two fold,
example :
table1 columns :
ssn : primary key
name : non-candidate key (names can repeat)
table2 columns
id2 : primary key
name_referencing : foreign key to name in table1 (is this foreign key possible??)
2.If the above case is possible, what happens when 'on delete cascade' happens. That is, if there are same values (in various rows) of the referenced column, does the deletion of the child(in referencing) happen only on the deletion of the last value(of the repeated values) in the referenced table ?
Upvotes: 0
Views: 651
Reputation: 51167
-- 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)
So, MySQL actually allows this situation. Weird. Oracle and PostgreSQL will not (both raise errors), and I don't believe the SQL standard allows it (but haven't checked, so could be wrong there). Let's see how it handles it:
-- 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)
So, MySQL deletes the row from the referencing table. At least in 5.1.49.
Upvotes: 1