Mysql: delete rows in two tables with foreign keys

Please try this, hope it will help.

DELETE FROM departure, departure_time
USING departure
INNER JOIN departure_time
WHERE departure_date = '2016-09-30'
      AND departure_time.id = departure.id

Or

DELETE FROM departure, departure_time
USING departure
INNER JOIN departure_time
WHERE departure_date = '2016-09-30'
      AND departure_time.departure_id = departure.id

Or you can use ON DELETE CASCADE that will do work automatically for you .


In MySQL, you can also delete from multiple tables in one statement:

delete d, dt
    from departure d join
         departure_time dt
         on d.id = dt.departure_id
    where departure_date = '2016-09-30';

Another solution is to declare the foreign key relationship as on delete cascade. Then when you delete the row in the original table, the database will delete the related records in the second table.

Tags:

Mysql