在MySQL

时间:2015-10-07 07:22:49

标签: mysql sql

我需要获取ID变体并删除除这些ID之外的所有记录。

我的SQL查询如下所示:

DELETE FROM catalog_variant WHERE id NOT IN (
  SELECT v.id FROM catalog_variant v
  JOIN catalog_product p ON p.id=v.id_product
  JOIN catalog_category_product_mm cpmm ON p.id=cpmm.id_product
  JOIN catalog_category c ON c.id=cpmm.id_category
  JOIN catalog_category_parameter_mm cparmm ON c.id=cparmm.id_category
  JOIN catalog_parameter par ON par.id=cparmm.id_parameter

  WHERE p.id=9 AND par.type=2 AND c.id IN(
    SELECT c.id FROM catalog_category_product_mm cpmm 
    JOIN catalog_category c ON c.id=cpmm.id_category 
    WHERE cpmm.id_product=9
  )
  GROUP BY v.id
);

我收到此错误:

  

您无法在FROM子句

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

你能帮我解决一下如何正确地做到这一点吗?

2 个答案:

答案 0 :(得分:1)

您可以将内部查询包装在临时表中,我在下面调用了temp。这样可以避免您看到的恼人的目标表错误消息。

DELETE FROM catalog_variant WHERE id NOT IN
(
    SELECT temp.id FROM
    (
        SELECT v.id AS id FROM catalog_variant v
        JOIN catalog_product p ON p.id=v.id_product
        JOIN catalog_category_product_mm cpmm ON p.id=cpmm.id_product
        JOIN catalog_category c ON c.id=cpmm.id_category
        JOIN catalog_category_parameter_mm cparmm ON c.id=cparmm.id_category
        JOIN catalog_parameter par ON par.id=cparmm.id_parameter
        WHERE p.id=9 AND par.type=2 AND c.id IN
        (
            SELECT c.id FROM catalog_category_product_mm cpmm 
            JOIN catalog_category c ON c.id=cpmm.id_category 
            WHERE cpmm.id_product=9
        )
        GROUP BY v.id
    ) temp
);

顺便说一下,Stack Overflow上已有一些非常好的资源可以解决这个问题,例如this one

答案 1 :(得分:0)

您可以使用a delete statement with a join

或者您可以先将ID放入临时表中。