【问题标题】:MySQL - Update multiple values and WHERE IN [duplicate]MySQL - 更新多个值和 WHERE [重复]
【发布时间】:2014-10-09 23:58:16
【问题描述】:

有没有像 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)

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

【问题讨论】:

  • 只需使用serialize()函数将数组转换为字符串,然后写入name列,读取数据时用户unserialize()将字符串转换为数组
  • 你误会了我的问题,我不想多次运行SQL
  • @AleksandarVasić 这违反了 RDBMS 的原则。

标签: php mysql sql database


【解决方案1】:

您在寻找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;

如果你有很多值,你可以分别用这些值创建一个表,然后进行更新。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 'abcd', 'efgh', 'ijkl'这样的东西怎么样
    猜你喜欢
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    相关资源
    最近更新 更多