当前位置: 代码网 > it编程>数据库>Mysql > MySQL 根据条件多值更新的实现

MySQL 根据条件多值更新的实现

2025年03月14日 Mysql 我要评论
mysql多条件批量更新核心语法:update 表名set 字段1 = case when 条件1 then 值1 when 条件2 then 值2

mysql多条件批量更新核心语法:

update 表名
set 
    字段1 = case 
        when 条件1 then 值1
        when 条件2 then 值2
        else 字段1 
    end,
    字段2 = case 
        when 条件1 then 值3
        when 条件2 then 值4
        else 字段2
    end
where 整体过滤条件;

示例场景:更新商品库存和价格

 
update products
set
    stock = case 
        when category_id = 5 and price > 100 then stock - 10
        when create_date < '2024-01-01' then stock + 5
        else stock
    end,
    price = case 
        when category_id = 5 then price * 0.9
        when stock > 1000 then price * 0.8
        else price
    end
where status = 'active';

高效写法技巧:

  • 批量更新逻辑
update users
set 
    vip_level = case
        when score >= 1000 then 'diamond'
        when score >= 500 then 'gold'
        else vip_level
    end,
    discount = case 
        when score >= 1000 then 0.7
        when score >= 500 then 0.8
        else discount
    end
where registration_year = 2024;

关键注意事项:

  • 条件优先级:when子句按书写顺序匹配
  • 必须包含else:防止意外覆盖数据,建议保留原值
  • 性能优化:where子句需使用索引字段
  • 事务处理:大批量更新建议分批次执行
  • 多表关联:可用join实现跨表条件更新
update orders o
join payments p on o.id = p.order_id
set 
    o.status = case 
        when p.paid = 1 then 'completed'
        else 'pending'
    end,
    p.processed_at = now()
where o.create_date > '2024-06-01';

扩展方案:使用if函数简化二元判断

update employees
set
    salary = if(performance > 90, salary * 1.2, salary),
    bonus = if(join_year < 2020, bonus + 5000, bonus)
where department = 'engineering';

建议根据实际数据量添加事务控制(begin/commit)和分页更新(limit),避免长时间锁表。

到此这篇关于mysql 根据条件多值更新的实现的文章就介绍到这了,更多相关mysql 多值更新内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com