Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse of ON DELETE CASCADE

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?

like image 789
Fragsworth Avatar asked Apr 06 '11 00:04

Fragsworth


People also ask

What is the function of on delete cascade on delete cascade?

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.

Is on delete cascade bad practice?

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.


1 Answers

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 ;
like image 197
neocanable Avatar answered Sep 28 '22 05:09

neocanable