我们想要的是更新t1表的column1为1,同时更新column2为2,但是sql写成了下面这样:
update t1 set column1 = 1 and column2 = 2 where id = 1;
第一感觉这个sql应该是错误的,因为and
的位置应该是逗号
。
但是执行的时候,没有错误,你可能还会发现影响行数为1。
分析: 先看数据:
mysql> select * from t1;
+------+---------+---------+
| id | column1 | column2 |
+------+---------+---------+
| 1 | 0 | 1 |
+------+---------+---------+
1 row in set (0.00 sec)
执行sql:
mysql> update t1 set column1 = 1 and column2 = 2 where id = 1;
Query OK, 0 rows affected (0.01 sec)
Rows matched: 1 Changed: 0 Warnings: 0
改写column2的值为1,在执行:
mysql> update t1 set column1 = 1 and column2 = 1 where id = 1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
影响行数为1, 看下数据:
mysql> select * from t1;
+------+---------+---------+
| id | column1 | column2 |
+------+---------+---------+
| 1 | 1 | 1 |
+------+---------+---------+
1 row in set (0.00 sec)
column1居然是1,猜测可能是布尔值,使用下面的sql测试:
mysql> update t1 set column1 = 0 and column2 = 1 where id = 1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
column1的值被更新为0了,所以猜测应该是正确的,再试一下下面的sql:
mysql> update t1 set column1 = 1 and column2 = 2 where id = 1;
column1的值仍然是0。
结论
其实最初的sql等于:
update t1 set column1 = (1 and column2 = 2) where id = 1;
也就是说column1的值是括号内逻辑运算的结果,即是布尔值。column2在这里只用来比较,不会做更新。开始影响行数为0,是因为column1的默认值就是0。
粗略翻了文档,没找到类似的说明。
所以要警惕这种写法。
(完)
- 本文作者:吴泽辉
- 本文链接:https://mutex.top/posts/20578cf7/
- 发表日期:2018年10月29日
- 版权声明:本文章为原创,采用《知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议》进行许可