How to specify target table for update in FROM clause for MYSQL?
Question
My script-:
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
)
)
It gives me following error-:
#1093 - You can't specify target table 'catalog_product_price' for update in FROM clause
Can anybody provide me solution for the same as I tried solution given on this link-: http://www.mysqlfaqs.net/mysql-faqs/Errors/1093-You-can-not-specify-target-table-comments-for-update-in-FROM-clause but unable to do... Please help me..
Solution
You need to join tables to the UPDATE statement instead of using all of those subqueries
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
note: Your syntax is quite difficult to read so I may have made a mistake interpreting it. Anyway, this is the idea and it should help you get to the final answer.
OTHER TIPS
Store the queried values in 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;
Note that your second inner query is nonsense - you are selecting column customer_group_id
whose value is already known because of the where clause WHERE customer_group_id = catalog_product_price.customer_group_id
... completely redundant