Search code examples
mysqlsqlsql-delete

MySQL - How to delete related rows in a many to many relationship


For example if a customer is deleted, all the related row on other table(S) will be deleted. How to do that mysql, it's a hours i tried many solution but noone worked.enter image description here


Solution

  • The easiest way to achieve that is design related tables with ON DELETE CASCADE option.

    Basically, when you design a database table that has a foreign key (primary key on other table), you can set ON DELETE CASCADE for that foreign key. That means that when a record is deleted on the primary table (the table where this foreign key is the primary key) all related records on other tables are also deleted.

    Therefore, you don't need to think on create "crazy" queries to delete related data on multiple tables.

    You can learn more about ON DELETE CASCADE here