1

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.

3 Answers 3

6
DELETE FROM orderdetail 
WHERE order_sequence_number IN 
(
    SELECT id 
    FROM orders 
    WHERE date_ordered BETWEEN X AND Y
)
Sign up to request clarification or add additional context in comments.

Comments

2

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
)

Comments

1

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
             )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.