一、测试数据构造
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()函数怎么失效了?