Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete rows from two tables in one query

Tags:

mysql

cascade

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?

like image 849
The Disintegrator Avatar asked Aug 27 '09 09:08

The Disintegrator


People also ask

How do I delete a row from two tables in SQL?

DELETE FROM table_name WHERE column_name BETWEEN value 1 AND value 2; Another way to delete multiple rows is to use the IN operator. DELETE FROM table_name WHERE column_name IN (value 1, value 2, value 3, etc...); If you want to delete all records from the table then you can use this syntax.

How can I delete data from two tables?

We often use the LEFT JOIN clause in the SELECT statement to find rows in the left table that have or don't have matching rows in the right table. We can also use the LEFT JOIN clause in the DELETE statement to delete rows in a table (left table) that does not have matching rows in another table (right table).

How do you delete data from 3 tables in SQL?

Try it like this: delete relativedata, crawls, stored from relativedata LEFT join crawls on relativedata. crawl_id = crawls.id LEFT join stored on relativedata. crawl_id = stored.


2 Answers

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'.

like image 181
Residuum Avatar answered Sep 23 '22 11:09

Residuum


You can define the table with ON DELETE CASCADE. If you do that, you only have to delete on the order table. The entries in other tables using order_id as foreign key with that option enabled will be deleted automagically.

This example is taken from the MySQL manual:

CREATE TABLE parent(
    id INT NOT NULL,
    PRIMARY KEY (id)
) ENGINE=INNODB;

CREATE TABLE child(
    id INT, parent_id INT,
    INDEX par_ind (parent_id),
    FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE
) ENGINE=INNODB;

Note that the engine is InnoDB.

like image 21
yeyeyerman Avatar answered Sep 23 '22 11:09

yeyeyerman