MySQL - 更新多个值和WHERE IN

时间:2014-08-16 12:27:20

标签: php mysql sql database

是否有像WHERE IN这样的语法允许我一次更新多个值? 例如:

update files
set name = 'untitled' 
WHERE id IN (1,2,3,4) 

成为:

update files
set name ( 'untitled', 'untitled2', 'untitled3', 'untitled4' )
WHERE id IN (1,2,3,4)

我的脚本包含一个关联数组,我需要更新名称列设置为数组值,其中id列与数组键匹配

2 个答案:

答案 0 :(得分:2)

您在寻找case声明吗?

update files
    set name = (case when id = 1 then 'untitled'
                     when id = 2 then 'untitled2'
                     when id = 3 then 'untitled3'
                     when id = 4 then 'untitled4'
                end)
    where id IN (1, 2, 3, 4);

在MySQL中,您也可以使用join

执行此操作
update files f join
       (select 1 as id, 'untitled' as newname union all
        select 2, 'untitled2' union all
        select 3, 'untitled3' union all
        select 4, 'untitled4'
       ) n
       on f.id = n.id
    f.name = new.newname;

如果您有很多值,可以单独创建一个包含值的表,然后进行更新。

答案 1 :(得分:0)

假设问题并未过分简化您的实际问题,您可以使用concat函数:

UPDATE files
SET    name = CONCAT('untitled', id)
WHERE  id IN (1,2,3,4)