Mysql: delete rows in two tables with foreign keys

前端 未结 3 1015
后悔当初
后悔当初 2021-01-03 03:04

I have two tables with data. I want to delete rows in both tables. But I have foreign keys between them. How can I do this?

 departure
     id    departure_d         


        
相关标签:
3条回答
  • 2021-01-03 03:44

    The multiple row delete failed for me because there were multiple rows in the second table referencing the first table. I was also unable to update the schema in order to add a foreign key constraint (as suggested in other answers).

    Using IN like so worked:

    DELETE FROM departure_time
    WHERE departure_id IN (
            SELECT departure_id
            FROM departure
            WHERE departure_date = '2016-09-30'
        );
    DELETE from departure
    WHERE departure_date = '2016-09-30'
    
    0 讨论(0)
  • 2021-01-03 04:00

    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.

    0 讨论(0)
  • 2021-01-03 04:03

    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 .

    0 讨论(0)
提交回复
热议问题