I am trying to figure out relationships and deletion options.
I have two tables, User
and UserStaff
, with a 1:n relationship from User
to UserStaff
(a user can have multiple staff members).
When my User
is deleted, I want to delete all of the UserStaff
tables associated with that User
. When my UserStaff
is deleted, I don't want anything to happen to User
. I understand that this is a cascading relationship, but I'm not sure which way.
i.e. Do I select the existing foreign key in my UserStaff
table and make it cascading, or do I create a new foreign key in User
and set that to cascading?
A foreign key with cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete in SQL Server.
When a referenced foreign key is deleted or updated, respectively, the columns of all rows referencing that key will be set to NULL . The column must allow NULL or this update will fail.
Use the ON DELETE CASCADE option to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behavior of the database server prevents you from deleting data in a table if other tables reference it.
Foreign keys cannot handle deletes and updates. Explanation: A foreign key is the one which declares that an index in one table is related to that in another and place constraints. It is useful for handling deletes and updates along with row entries.
Yes, it's possible. You should make the FK in UserStaff table. In this way:
User Table
CREATE TABLE `User` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `Name` varchar(255) DEFAULT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
UserStaff Table
CREATE TABLE `UserStaff` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `UserId` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`Id`), KEY `UserId` (`UserId`), CONSTRAINT `UserStaff_ibfk_1` FOREIGN KEY (`UserId`) REFERENCES `User` (`Id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
From Wikipedia:
CASCADE
Whenever rows in the master (referenced) table are deleted (resp. updated), the respective rows of the child (referencing) table with a matching foreign key column will get deleted (resp. updated) as well. This is called a cascade delete (resp. update[2]).
Here, User
is the master table, and UserStaff
is the child table. So, yes, you'll want to create the foreign key in UserStaff
, with ON DELETE CASCADE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With