如何在MYSQL的FROM子句中指定更新目标表?

时间:2012-04-04 14:52:55

标签: mysql sql clause

我的剧本 - :

UPDATE catalog_product_price 
SET catalog_product_price.value = 200
WHERE value_id = (
    SELECT value_id
    FROM catalog_product_price
    WHERE `entity_id` = ( 
        SELECT `entity_id` 
        FROM `catalog_product_entity` 
        WHERE `sku` LIKE 'sample'
        ) 
    AND website_id = 10
    AND customer_group_id= (
        SELECT customer_group_id
        FROM customer_group
        WHERE 
            customer_group_id = catalog_product_price.customer_group_id 
            AND customer_group_code =100
        )
    )

它给了我以下错误 - :

  

#1093 - 您无法在FROM子句中为更新指定目标表'catalog_product_price'

任何人都能为我提供解决方案,就像我在此链接上尝试的解决方案一样 - : http://www.mysqlfaqs.net/mysql-faqs/Errors/1093-You-can-not-specify-target-table-comments-for-update-in-FROM-clause 但无法做到...... 请帮帮我..

2 个答案:

答案 0 :(得分:5)

您需要将表连接到UPDATE语句,而不是使用所有这些子查询

UPDATE  catalog_product_price cpp

JOIN    catalog_product_entity cpe
  ON    cpe.entity_id = cpp.entity_id
  AND   cpe.sku LIKE 'sample'
  AND   website_id = 10

JOIN    customer_group cg
  ON    cg.customer_group_id = cpp.customer_group_id
  AND   cg.customer_group_code = 100

SET cpp.value = 200

注意:您的语法很难阅读,所以我可能在解释它时犯了错误。无论如何,这是一个想法,它应该帮助你得到最终答案。

答案 1 :(得分:3)

将查询的值存储在user defined variables

set @value_id := (
    SELECT value_id
    FROM catalog_product_price
    WHERE `entity_id` = ( 
        SELECT `entity_id` 
        FROM `catalog_product_entity` 
        WHERE `sku` LIKE 'sample'
    );
set @customer_group_id := (
    SELECT customer_group_id
    FROM catalog_product_price
    WHERE `entity_id` = ( 
        SELECT `entity_id` 
        FROM `catalog_product_entity` 
        WHERE `sku` LIKE 'sample'
    );

UPDATE catalog_product_price 
SET catalog_product_price.value = 200
WHERE value_id = @value_id 
AND website_id = 10
AND customer_group_id = @customer_group_id;

请注意,您的第二个内部查询是无意义的 - 您正在选择其值已知的列customer_group_id,因为where子句WHERE customer_group_id = catalog_product_price.customer_group_id ...完全冗余