0

I have a database called music and have 4 tables inside;

  1. band_members
  2. bands
  3. cds
  4. releases.

I want to delete all information relating to cd005 (that's a cd_id column entry) in the database.

I guess I could use the

DELETE FROM table_name WHERE cd_id='cd005'

on every individual table, but I would like to know if there's a way to tackle this problem by deleting the data related to this id from the whole database at once.

1 Answer 1

1

Yes there is a way. Please check mysql documantation for foreign keys cascade deletes.

Example:

CREATE TABLE parent (id INT NOT NULL,
                     PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
                    INDEX par_ind (parent_id),
                    FOREIGN KEY (parent_id) REFERENCES parent(id)
                      ON DELETE CASCADE
) ENGINE=INNODB;

Insert into parent set id=1;
Insert into parent set id=2;
Insert into parent set id=3;
Insert into child set id=1, parent_id=1;
Insert into child set id=2, parent_id=1;


select * from parent;
select * from child;
delete from  parent where id=1;
select * from parent;
select * from child;


ID
1
2
3
 Record Count: 3; Execution Time: 0ms View Execution Plan
ID  PARENT_ID
1   1
2   1
 Record Count: 2; Execution Time: 0ms View Execution Plan
 Record Count: 0; Execution Time: 1ms
ID
2
3
 Record Count: 2; Execution Time: 0ms View Execution Plan
 Record Count: 0; Execution Time: 0ms
Sign up to request clarification or add additional context in comments.

2 Comments

I would go with the cascading
How can I use the cascade delete? I can see from my tables that I have the cd_id as a primary key in my cds table. I suppose if I delete that, all child entries should be also deleted?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.