Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Delete with 1 to 1 relation

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?

Edit : Problem with delete cascade

I need both of the keys because there is actually 2 relations. Lets be more practical :

  • the table 1 is a "drop down list" that has a default value.
  • the table 2 has every values possible for each DDL in table 1.

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.

like image 679
Nicolas Thery Avatar asked Dec 01 '25 10:12

Nicolas Thery


1 Answers

You have two options here:

  1. Alter the foreign key definition to also delete referenced rows. This can be done with ON DELETE CASCADE.
  2. Use a transaction around the two delete statements.

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;
like image 146
H-Man2 Avatar answered Dec 02 '25 23:12

H-Man2