在一个查询中使用UPDATE,CASE和LEFT JOIN的MySQL查询

时间:2018-09-28 07:00:17

标签: mysql join case

试图使“ UPDATE”,“ SET”与“ CASES”和LEFT JOIN结合使用,有人能帮助我吗?

UPDATE `cataloginventory_stock_item`         
SET `csi`.`qty` = 
    CASE 
        WHEN `cpe`.`sku` = '03352828' THEN '1000'
        WHEN `cpe`.`sku` = '04975135' THEN '15150'  
    END
FROM `cataloginventory_stock_item` csi
LEFT JOIN `catalog_product_entity` cpe 
ON `csi`.`product_id` = `cpe`.`entity_id`

但是会引发语法错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use 
near 'FROM `cataloginventory_stock_item` csi LEFT JOIN `catalog_product_entity` cpe O' at line 7 

将有助于大大减少UPDATE查询量。

1 个答案:

答案 0 :(得分:1)

您不能在FROM查询中使用UPDATE子句。在Update中,您必须“收集”表,然后使用SET

执行以下操作:

UPDATE `cataloginventory_stock_item` AS csi 
LEFT JOIN `catalog_product_entity` cpe 
ON `csi`.`product_id` = `cpe`.`entity_id` 
SET `csi`.`qty` = 
    CASE 
        WHEN `cpe`.`sku` = '03352828' THEN '1000'
        WHEN `cpe`.`sku` = '04975135' THEN '15150'  
    END

Syntax of Update clause

UPDATE [LOW_PRIORITY] [IGNORE] table_reference
    SET assignment_list
    [WHERE where_condition]
    [ORDER BY ...]
    [LIMIT row_count]

value:
    {expr | DEFAULT}

assignment:
    col_name = value

assignment_list:
    assignment [, assignment] ...