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?
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.
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).
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.
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'
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With