Morning,
I have three tables:
Table: debtors
id - INT(11)
type - ENUM('c', 'p')
Table: companies
id - INT(11)
debtor_id - INT(11)
and a lot of other fields for companies
Table: private_individuals
id - INT(11)
debtor_id - INT(11)
and a lot of other fields for private individuals
Foreign KEY SQL for companies(same is used for private individuals):
INDEX `fk_private_individual_debtors1` (`debtor_id` ASC) ,
CONSTRAINT `fk_private_individual_debtors1`
FOREIGN KEY (`debtor_id` )
REFERENCES `application_user`.`debtors` (`id` )
ON DELETE CASCADE
ON UPDATE NO ACTION)
When I delete a company or private individual I want the debtor to be deleted as well and it should work the other way around aswell(delete a debtor and the company or private individual is deleted aswell).
I’m thinking to do this with a trigger but I suppose there is a better way to do it..
Can anyone help please?
This can be done by
ON DELETE CASCADE. You specify this when you define the foreign key, and applies to all deletes on the table. You cannot mention this at the indivudual DELETE level. See FOREIGN KEY Constraints in the MySql manualRemember this is dangerous in most cases and you are better off having this logic in your application code.
This is not directly possible. You have built a foreign key relationship between a company and a debtor but there can be more than one company associated to the debtor. There is nothing in the foreign key that prevents this. You may have additional application logic (in a procedure, in your java/C# code, in triggers) but there is nothing in the foreign key level at all.
So since this is acheived by additional application logic your deletion also will need additional application logic.
One another point to note is: you should delete a [arent only if all of its child records are deleted.