Delete rows from two tables in one query

后端 未结 5 960
[愿得一人]
[愿得一人] 2021-02-09 08:43

I have two tables: orders and orders_items. Both sharing the field orderID.

I want to delete all rows from both tables where orderID=500, but I need to do this in only o

5条回答
  •  醉梦人生
    2021-02-09 09:31

    Here's a simply solution if you're using MySQL/PgSQL...

    DELETE t1, t2 FROM table1 AS t1 
    LEFT JOIN table2 AS t2 USING( orderID ) 
    WHERE t1.orderID = 500;
    

    Guaranteed to work like a charm!

    Make sure to replace table1 and table2 with appropriate table names in your case.

    I've used plenty of this query in my custom designed CMS - wherever I've wanted to avoid two distinct atomic queries. This is as good as a cascading delete and the query can be expanded to span over as many tables as you want.

    Here's another example involving 3 tables:

    DELETE t1, t2, t3 FROM table1 AS t1 
    LEFT JOIN table2 AS t2 USING( orderID ) 
    LEFT JOIN table3 AS t3 USING( orderID ) 
    WHERE t1.orderID = 500;
    

    Cheers, m^e

提交回复
热议问题