0

I have 3 tables: categories, posts and comments.

categories and posts are connected via categories.id_category = posts.category_id and posts and comments are connected via posts.id_post = comments.post_id.

When I delete category, I want also to delete all the posts related to that category and all comments related to that posts. Can this be done in one query?

3
  • The best way would be to create your tables with foreign keys and use references in tables -> called referential integrity. Take a look at dev.mysql.com/tech-resources/articles/… Maybe this is the right thing for you Commented Jul 8, 2014 at 11:36
  • Yes. It can. With or without referential integrity Commented Jul 8, 2014 at 11:43
  • And if you do not want foreign key and want to do other way use trigger to handle it. Commented Jul 8, 2014 at 11:43

1 Answer 1

3

MySQL InnoDB databases support the FOREIGN KEY constraint with ON DELETE CASCADE clause. With this specifications, related dependent table rows will be deleted when doing a DELETE on the referred table.

This is an example:

CREATE TABLE categories (
    id_category int unsigned not null primary key,
    ...
);
CREATE TABLE posts (
    id_post int unsigned not null primary key,
    category_id int unsigned not null,
    ...
    FOREIGN KEY (category_id) REFERENCES categories (id_category)
       ON DELETE CASCADE
);
CREATE TABLE comments (
    post_id int unsigned not null,
    ...
    FOREIGN KEY (post_id) REFERENCES posts (id_post)
       ON DELETE CASCADE
);

Here you can find documentation about the use of foreign keys in MySQL: http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html

Sign up to request clarification or add additional context in comments.

4 Comments

So, the logic is that I only need to delete category and all the posts and comments will be auto deleted?
Yes, you can do a single DELETE on the categories table and all referenced rows will be deleted too. I clarified this in the answer.
Cool :). Can I alter my tables or I need to create new ones in order for the foreign key to work?
You can alter tables, for example: ALTER TABLE posts ADD INDEX (category_id); to add the index, then ALTER TABLE posts ADD FOREIGN KEY (category_id) REFERENCES categories ( id ) ON DELETE CASCADE ON UPDATE NO ACTION ;

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.