在日常开发中,更新数据(update) 是仅次于 select 的常用 sql 操作。
无论是修改用户昵称、调整库存数量,还是批量修正数据错误,都离不开 update 语句。
本文将带你全面掌握 单列更新、多列更新 的正确写法,并结合实际场景给出优化建议。
一、update 基本语法
update 的基本语法如下:
update table_name set column1 = value1, column2 = value2, ... where condition;
👉 其中:
● table_name 表示要更新的表;
● set 用来指定要修改的字段及新值;
● where 用来指定更新的范围(必须注意条件,否则可能全表更新)。
二、更新单列数据
如果只需要修改某个字段,可以这样写:
-- 将 id=1 的用户昵称改为 tom update user set name = 'tom' where id = 1;
👉 使用场景:修改单个字段(比如用户名、状态值等)。
三、更新多列数据
update 支持同时修改多个字段,用逗号分隔即可:
-- 修改 id=2 的用户昵称和年龄 update user set name = 'jerry', age = 18 where id = 2;
👉 使用场景:一次更新多列,减少 sql 执行次数。
四、带条件的更新
update 语句通常要结合 where 条件,否则可能导致 全表更新。
1. 根据条件批量更新
-- 将所有 age < 20 的用户状态改为 'teen' update user set status = 'teen' where age < 20;
2. 根据子查询更新
-- 将订单表中 amount > 1000 的用户标记为 vip update user set level = 'vip' where id in ( select user_id from orders where amount > 1000 );
👉 注意:子查询要确保执行效率,否则可能拖慢更新。
五、常见误区 ⚠️
1. 忘记写 where 条件
update user set age = 18; -- 全表更新,危险!
2. 用错运算符
update user set age = age + 1; -- 正确,表示年龄加 1 update user set age = 'age + 1'; -- 错误,变成字符串
3. 一次更新过多数据
在大数据表中,update 会加锁,影响并发性能;
建议分批更新,比如每次更新 1000 条。
六、update 的性能优化
1. 加索引
确保 where 条件字段有索引,否则更新可能会全表扫描。
2. 分批更新
大表更新建议使用 limit 分批:
update user set status = 'inactive' where status = 'active' limit 1000;
3. 避免触发全表锁
如果更新条件不精准,可能导致大面积锁表,影响其他业务。
4. 使用事务
批量更新时用事务保证数据一致性:
start transaction; update user set status = 'vip' where id between 100 and 200; commit;
七、总结
update 是修改数据的核心语句,常见于单列更新、多列更新。
必须带 where 条件,避免全表更新的严重后果。
大数据更新要注意 索引、分批更新、事务,提升性能和安全性。
灵活运用子查询,可以实现跨表条件更新。
掌握这些技巧,你的 sql 更新操作将更高效、更安全。 🚀
👉 你在项目中是否遇到过 全表更新误操作 的坑?是如何避免的?欢迎在评论区分享经验,一起交流!
到此这篇关于sql update 语句详解更新单列、多列的写法的文章就介绍到这了,更多相关sql update语句内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论