MySQL排查|update的字段值怎么变成0或1了?

一、测试数据构造

mysql> create table sky (id int,name varchar(10),score int);Query OK, 0 rows affected (0.02 sec)
mysql> insert into sky select 4,'a',4;Query OK, 1 row affected (0.01 sec)Records: 1  Duplicates: 0  Warnings: 0
mysql> insert into sky select 3,'b',1;Query OK, 1 row affected (0.00 sec)Records: 1  Duplicates: 0  Warnings: 0
mysql> insert into sky select 2,'b',5;Query OK, 1 row affected (0.01 sec)Records: 1  Duplicates: 0  Warnings: 0
mysql> insert into sky select 1,'c',6;Query OK, 1 row affected (0.00 sec)Records: 1  Duplicates: 0  Warnings: 0
mysql> mysql> select * from sky;+------+------+-------+| id   | name | score |+------+------+-------+|    4 | a    |     4 ||    3 | b    |     1 ||    2 | b    |     5 ||    1 | c    |     6 |+------+------+-------+4 rows in set (0.00 sec)

二、故障复现

mysql> update sky set score=10 and name='b' where id in (1,2,3);Query OK, 2 rows affected (0.00 sec)Rows matched: 3  Changed: 2  Warnings: 0
mysql> select * from sky;+------+------+-------+| id   | name | score |+------+------+-------+|    4 | a    |     4 ||    3 | b    |     1 ||    2 | b    |     1 ||    1 | c    |     0 |+------+------+-------+4 rows in set (0.00 sec)

可以看到,本意是想将id 为1,2,3时,score和name的值全部更新掉,却误将score的值update为0或1。

三、原因剖析

update多个列时,理应用【,】隔开而不是【and】隔开。

若使用了and则会将(10 and name='b')看作一个整体,此时and是一个逻辑运算符,首先10本身为true,再逐行判断name='b'是否为true,为true时整体结果为1,即上述结果id=2,3时score的值被更新为1;id=1 为false时,score的值被更新为0。

四、复盘总结

1、数据变更需要在测试环境提前验证,否则出现意想不到的结果

2、update在set多个列时注意要用【,】隔开。

mysql11

mysql · 目录

上一篇MySQL分享|8.0版本数据库unhex()函数怎么失效了?

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值