MySQL - 更新多个值和 WHERE IN [英] MySQL - Update multiple values and WHERE IN
本文介绍了MySQL - 更新多个值和 WHERE IN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有像 WHERE IN 这样的语法允许我一次更新多个值?例子:
Is there any syntax like WHERE IN allow me to update multiple values at once? example:
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 列与数组键匹配
My script contains an associative array, I need to update the name column set as array value where the id column match the array key
推荐答案
您在寻找 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
来做到这一点:
In MySQL, you can also do this with a 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;
如果您有很多值,您可以分别用这些值创建一个表,然后进行更新.
If you have a lot of values, you can create a table with the values separately and then do the update.
这篇关于MySQL - 更新多个值和 WHERE IN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文