使用嵌套选择查询删除MySQL

时间:2011-09-04 10:13:58

标签: mysql sql-delete

我有以下MySQL查询:

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')
  )
)

但是当我尝试执行时,我收到以下错误消息:

  

您无法在FROM子句

中为更新指定目标表'catalog'

有人可以告诉我哪里出错吗?

2 个答案:

答案 0 :(得分:16)

执行双重嵌套

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
)

愚弄mysql

答案 1 :(得分:5)

或者你可以使用临时表:

  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);

根据您的查询,您获得了You can't specify target table 'catalogue' for update in FROM clause,因为您无法在一个查询中对同一个表进行选择和更新。