简体   繁体   中英

SQL-Delete from a table based on a nested query

I have three tables in a mySQL databse as such:

orders: order_sequence_number, contact_id, date_ordered ...

orderdetail: order_sequence_number ...

person: contact_id ...

I am trying to delete all rows across the three tables that have a date_ordered value older than two years, however, the date_ordered field only appears in the orders table but the table has links to the other two via the order_sequence_number and contact_id fields.

So, i'd image a bit like this: ...

SELECT * FROM orders WHERE date_ordered BETWEEN X AND Y

Then with that record set

DELETE FROM orderdetail WHERE orderdetail.order_sequence_number IN (THE ABOVE)

Etc for persons table ... but having no luck.

Seems to me like some sort of nested subquery but I am having difficulty understanding how to do such a query and cant get my head around the convoluted nature of it...

Any pointers would be very much appreciated.

DELETE FROM orderdetail 
WHERE order_sequence_number IN 
(
    SELECT id 
    FROM orders 
    WHERE date_ordered BETWEEN X AND Y
)

thats pretty much what you wrote:

DELETE FROM orderdetail WHERE orderdetail.order_sequence_number IN (
    SELECT distinct(order_sequence_number) FROM orders WHERE date_ordered BETWEEN X AND Y
)

If you have a big table orders , it's better to use EXISTS

DELETE FROM orderdetail od 
WHERE EXISTS ( SELECT NULL 
               FROM orders o 
               WHERE date_ordered BETWEEN X AND Y
                 and od.order_sequence_number = o.order_sequence_number
             )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM