Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to empty a self-referential MySQL table?

Tags:

I have a self-referential MySQL table with a recursive parent_id:

CREATE TABLE `recursive` (   `id` int(11) NOT NULL auto_increment,   `parent_id` int(11) default NULL,   `name` varchar(100) NOT NULL,   PRIMARY KEY  (`id`),   KEY `data_categorysource_parent_id` (`parent_id`),   CONSTRAINT `parent_id_refs_id_627b4293`     FOREIGN KEY (`parent_id`) REFERENCES `data_categorysource` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 

During testing, I want to empty it but TRUNCATE fails:

TRUNCATE `recursive`  /* SQL Error: Cannot delete or update a parent row: a foreign key constraint fails... 

I currently have to manually delete all records, starting at the bottom of the tree working upwards. This gets onerous even with small trees.

Is there an easy way around this? I can't DROP the table and re-create it easily as other tables reference it (I have already truncated those so there should be no data integrity issues there).

like image 715
Mat Avatar asked Mar 05 '09 17:03

Mat


People also ask

How do you delete a table that has a foreign key reference?

To delete a foreign key constraintIn Object Explorer, expand the table with the constraint and then expand Keys. Right-click the constraint and then click Delete. In the Delete Object dialog box, click OK.

How do I empty a table in MySQL workbench?

To remove a table in MySQL, use the DROP TABLE statement. The basic syntax of the command is as follows: DROP [TEMPORARY] TABLE [IF EXISTS] table_name [, table_name] [RESTRICT | CASCADE];

What if I delete a row containing a foreign key to another table?

Table student_exam has foreign key student_id referencing student_id in student_details table. Here, ON DELETE CASCADE is added because when any row is deleted in one table the same gets deleted in the foreign referenced tables that are referencing the primary key in that table.

How do I remove a foreign key from a column in MySQL?

Dropping Foreign Key Constraints You can drop a foreign key constraint using the following ALTER TABLE syntax: ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol; If the FOREIGN KEY clause defined a CONSTRAINT name when you created the constraint, you can refer to that name to drop the foreign key constraint.


2 Answers

Why not:

UPDATE 'recursive' SET 'parent_id' = NULL WHERE 'parent_id' IS NOT NULL; DELETE FROM 'recursive'; 

?

like image 165
Craig Stuntz Avatar answered Jan 31 '23 18:01

Craig Stuntz


If you just want to empty the whole thing for testing purposes use:

SET FOREIGN_KEY_CHECKS = 0;  // Execute Query  SET FOREIGN_KEY_CHECKS = 1; 

This totally bypasses any foreign key checks.

like image 42
Noah Goodrich Avatar answered Jan 31 '23 17:01

Noah Goodrich