12

I have the following MySQL query:

DELETE FROM catalogue 
WHERE catalogue_id IN (
  SELECT catalogue_id 
  FROM catalogue 
  WHERE (
    product_id = (SELECT product_id FROM catalogue WHERE catalogue_id = '2290') 
    AND length_id = (SELECT length_id FROM catalogue WHERE catalogue_id = '2290') 
    AND gauge_id = (SELECT gauge_id FROM catalogue WHERE catalogue_id = '2290')
  )
)

But when I attempt to execute I get the following error message:

You can't specify target table 'catalogue' for update in FROM clause

Could someone advise on where I'm going wrong?

2 Answers 2

19

Perform double nesting

DELETE FROM catalogue 
WHERE catalogue_id IN (SELECT catalogue_id FROM (
  SELECT catalogue_id 
  FROM catalogue 
  WHERE (
    product_id = (SELECT product_id FROM catalogue WHERE catalogue_id = '2290') 
    AND length_id = (SELECT length_id FROM catalogue WHERE catalogue_id = '2290') 
    AND gauge_id = (SELECT gauge_id FROM catalogue WHERE catalogue_id = '2290')
  )) x
)

It fools mysql

Sign up to request clarification or add additional context in comments.

6 Comments

Works perfectly zerkms, but what's the reason for having to 'fool' MySQL?
What about if you have more than one WHERE column? i.e. DELETE FROM catalogue WHERE catalogue_id AND catalogue_name IN...
@ThreaT: I'm not sure what you're asking about. Multiple predicates may be added with ADD, yes.
How would you change your answer to use ADD?
It's been 9 years and still need this hackery.
|
5

Or you can use temporary table:

  CREATE TEMPORARY TABLE t AS
  SELECT catalogue_id 
  FROM catalogue 
  WHERE (
    product_id = (SELECT product_id FROM catalogue WHERE catalogue_id = '2290') 
    AND length_id = (SELECT length_id FROM catalogue WHERE catalogue_id = '2290') 
    AND gauge_id = (SELECT gauge_id FROM catalogue WHERE catalogue_id = '2290')
  );

  DELETE FROM catalogue WHERE catalogue_id IN (SELECT catalogue_id FROM t);

With your query you got You can't specify target table 'catalogue' for update in FROM clause because you can't make select and update on the same table in one query.

1 Comment

Thanks Kamil for the explanation.

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.