Delete rows from two tables in one query

The Disintegrator picture The Disintegrator · Aug 27, 2009 · Viewed 8.5k times · Source

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 one query. Is this possible?

Answer

Residuum picture Residuum · Aug 27, 2009

Surely you can do that:

DELETE FROM `table1`, `table2` WHERE `orderId` = 500

see http://dev.mysql.com/doc/refman/5.0/en/delete.html

[EDIT:]

This is the whole trick:

DELETE FROM `orders`, `orders_items` 
  USING `orders` 
  INNER JOIN `orders_items` ON `orders`.`orderId` = `orders_items`.`orderId` 
  WHERE `orders`.`orderId`= 500

If orderId is a varchar, then change the statement to = '500'.