本文介绍mysql中批量更新数据的几种常用方法:
1. 使用 case when 语句(推荐)
update users
set
status = case id
when 1 then 'active'
when 2 then 'inactive'
when 3 then 'pending'
end,
updated_at = case id
when 1 then '2024-01-01'
when 2 then '2024-01-02'
when 3 then '2024-01-03'
end
where id in (1, 2, 3);
2. 使用多个 when then 条件
update products
set
price = case
when id = 1 then 19.99
when id = 2 then 29.99
when id = 3 then 39.99
else price
end,
stock = case
when id = 1 then 100
when id = 2 then 50
when id = 3 then 200
else stock
end
where id in (1, 2, 3);
3. 使用 values 和 join 方式
update orders o
join (
select 1 as id, 'shipped' as status, '2024-01-01' as ship_date
union all
select 2, 'processing', '2024-01-02'
union all
select 3, 'delivered', '2024-01-03'
) as temp on o.id = temp.id
set
o.status = temp.status,
o.ship_date = temp.ship_date,
o.updated_at = now();
4. 使用临时表方式
-- 创建临时表
create temporary table temp_updates (
id int primary key,
name varchar(100),
email varchar(100)
);
-- 插入要更新的数据
insert into temp_updates values
(1, '张三', 'zhangsan@email.com'),
(2, '李四', 'lisi@email.com'),
(3, '王五', 'wangwu@email.com');
-- 执行批量更新
update users u
join temp_updates t on u.id = t.id
set
u.name = t.name,
u.email = t.email,
u.updated_at = now();
-- 删除临时表
drop temporary table temp_updates;
5. 使用 insert … on duplicate key update
适用于主键或唯一索引冲突时的更新:
insert into users (id, name, email, status, updated_at)
values
(1, '张三', 'zhangsan@email.com', 'active', now()),
(2, '李四', 'lisi@email.com', 'inactive', now()),
(3, '王五', 'wangwu@email.com', 'active', now())
on duplicate key update
name = values(name),
email = values(email),
status = values(status),
updated_at = now();
6. 批量更新相同值
-- 更新所有符合条件的记录为相同值
update products
set
category = 'electronics',
updated_at = now()
where id in (1, 2, 3, 4, 5);
-- 基于条件的批量更新
update employees
set
salary = salary * 1.1, -- 涨薪10%
last_raise_date = now()
where department = 'engineering'
and performance_rating >= 4;
7. 使用存储过程进行复杂批量更新
delimiter //
create procedure batchupdateusers()
begin
declare done int default false;
declare user_id int;
declare user_status varchar(20);
declare cur cursor for select id, status from users where status = 'pending';
declare continue handler for not found set done = true;
open cur;
read_loop: loop
fetch cur into user_id, user_status;
if done then
leave read_loop;
end if;
-- 根据业务逻辑更新
update users
set status = 'processed', processed_at = now()
where id = user_id;
end loop;
close cur;
end //
delimiter ;
-- 调用存储过程
call batchupdateusers();
性能优化建议
- 添加索引:在 where 条件的字段上添加索引
- 分批处理:大量数据时建议分批更新
- 事务控制:使用事务确保数据一致性
start transaction; update large_table set status = 'updated' where id between 1 and 10000; update large_table set status = 'updated' where id between 10001 and 20000; commit;
注意事项
- 批量更新前建议先备份数据
- 在生产环境执行前先在测试环境验证
- 注意 where 条件,避免误更新
- 大量数据更新时考虑在业务低峰期执行
选择哪种方法取决于具体需求、数据量和性能要求。case when 方式通常是最常用且性能较好的选择。
到此这篇关于mysql中批量更新数据的几种常用方法的文章就介绍到这了,更多相关mysql批量更新数据内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论