My database is MySQL with foreign key management. It has 2 tables :
Table1 :
|id|foreignKeyToTable2|data...|
Table2 :
|id|foreignKeyToTable1|data...|
I want to delete a couple of these lines but when I delete one of them I have the meaningful foreign key error.
How can I delete the couple of lines in one time?
Am I forced to disable foreign key checks?
I need both of the keys because there is actually 2 relations. Lets be more practical :
Tables are :
DDL
|id|name|defaultValue (FK delete cascade)|
Value
|id|name|DDLiD (FK)|
Following your answers, I added a DELETE CASCADE to the DDL table. But I still have a FK error .
Cannot delete or update a parent row: a foreign key constraint fails (Value, CONSTRAINT fk_Value_DDL FOREIGN KEY (DDL) REFERENCES DDL (id) ON DELETE NO ACTION ON UPDATE NO ACTION)
I don't want to add a delete cascade on the Value table because i want to be able to delete a value.
You have two options here:
ON DELETE CASCADE. The second option is my prefered one, because a database user is informed about the usage in the other table and can then decide to use a transaction to remove data from both rows.
Also, one usage scenario of a 1:1 relation is to allow different permissions on both tables. When using delete cascade I don't know if these are checked.
EDIT
After I was pointed that MySQL is handling foreign key checking not as stated in the SQL standards, my second option is changed to:
2. Because MySQL does not support deferred checking of foreign key constraints while using transactions (this is a deviation from SQL standards), you need to disable foreign key checks for the delete statements:
SET foreign_key_checks = 0;
DELETE ...;
SET foreign_key_checks = 1;
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