一个查询中的多个更新位置 - 高效结构

时间:2014-05-25 23:12:49

标签: mysql sql

我尝试使用典型的update where语法更新大量行。

为了保持一致,我把这个查询放在了一起,但它不起作用(在第一个括号中失败)

UPDATE product_options 
SET 
    (object_id=14,option_key='size_small',option_name='Size Small',option_description='This is the small size...',option_price=2.50),
    (object_id=14,option_key='size_medium',option_name='Size Medium',option_description='This is the medium size...',option_price=5.50),
    (object_id=14,option_key='size_large',option_name='Size Large',option_description='This is the large size...',option_price=10.50),
    (object_id=14,option_key='size_really_big',option_name='Size Really Big',option_description='This is the really big size...',option_price=20.50)

WHERE (option_id=1), (option_id=2), (option_id=3), (option_id=4)

每个SET语句都有一个相应的WHERE语句。那么这里出了什么问题?


编辑:

根据提供的答案,这是最终完成的完整查询:

UPDATE `product_options` SET

`object_id` = 14,

`option_key` = CASE
WHEN `option_id`='1' THEN 'size_small'
WHEN `option_id`='2' THEN 'size_medium'
WHEN `option_id`='3' THEN 'size_large'
ELSE `option_key` END,

`option_name` = CASE
WHEN `option_id`='1' THEN 'Small'
WHEN `option_id`='2' THEN 'Medium'
WHEN `option_id`='3' THEN 'Larger'
ELSE `option_name` END,

`option_price` = CASE
WHEN `option_id`='1' THEN 5.50
WHEN `option_id`='2' THEN 10.00
WHEN `option_id`='3' THEN 21
ELSE `option_price` END

WHERE `option_id`='1' OR `option_id`='2' OR `option_id`='3'

1 个答案:

答案 0 :(得分:2)

这不是它的工作原理。如果您愿意,可以使用CASE语句:

UPDATE product_options 
SET 
    object_id=14,
    option_key=
        case when option_id =  1 
             then 'size_small'
             when option_id = 2
             then 'size_medium'
             when option_id = 3
             then 'size_large'
             when option_id = 4
             then 'size_really_big'
        end, 
    ....
WHERE option_id IN (1,2,3,4)

您还可以使用联接,例如:

UPDATE product_options po
    JOIN (
        SELECT 1 option_id, 'size_small' option_key, 'Size Small' option_name
        UNION ALL
        SELECT 2 option_id, 'size_medium' option_key, 'Size Medium' option_name
        ...
    ) temp ON po.option_id = temp.option_id
SET po.object_id = 14,
    po.option_key = temp.option_key,
    po.option_name = temp.option_name