Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL delete with nested select query

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?

like image 700
bland_dan Avatar asked Sep 04 '11 10:09

bland_dan


People also ask

Can we use DELETE in subquery?

DELETE operations with subqueries that reference the same table object are supported only if all of the following conditions are true: The subquery either returns a single row, or else has no correlated column references. The subquery is in the DELETE statement WHERE clause, using Condition with Subquery syntax.

How do I DELETE multiple records from a table in SQL?

There are a few ways to delete multiple rows in a table. If you wanted to delete a number of rows within a range, you can use the AND operator with the BETWEEN operator. 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.


2 Answers

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

like image 150
zerkms Avatar answered Oct 06 '22 10:10

zerkms


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.

like image 34
Kamil Dziedzic Avatar answered Oct 06 '22 10:10

Kamil Dziedzic