Suppose I have the following schema:
CREATE TABLE `users` (
`id` int(10) unsigned auto_increment,
`historyId` varchar(255),
PRIMARY KEY (`id`)
);
CREATE TABLE `histories` (
`id` int(10) unsigned auto_increment,
`history` TEXT,
PRIMARY KEY (`id`)
);
A User only ever has one History, and the purpose of not having histories point to users is that many other tables (not mentioned in this schema) also have histories.
What's the simplest way to make it so that deleting a User will also delete its History?
ON DELETE CASCADE constraint is used in MySQL to delete the rows from the child table automatically, when the rows from the parent table are deleted.
Yes, the use of ON DELETE CASCADE is fine, but only when the dependent rows are really a logical extension of the row being deleted. For example, it's OK for DELETE ORDERS to delete the associated ORDER_LINES because clearly, you want to delete this order, which consists of a header and some lines.
You can use trigger like this:
DELIMITER $$
CREATE TRIGGER delete_user_history_on_delete_user
AFTER DELETE ON `users`
FOR EACH ROW
BEGIN
DELETE FROM `histories` WHERE id = old.historyId;
END$$
DELIMITER ;
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