Mysql 容易犯错的update and操作
使用sql语句在对多个值update 时,有时可能误将',' 写成了'and'。
**先看看两个语句的区别,我们目的要将beijing 表id<=2 的uid gid 的值各+1000 :**
```
#1 update beijing set uid = uid + 1000 and gid = gid + 1000 where id <= 2 ;
#2 update beijing set uid = uid + 1000, gid = gid + 1000 where id <= 2 ;
```
1、首先看数据:
![](https://image.xsoftlab.net/baike/articleImages/14415e7b1394c13d1cf35c41b20444e3.jpg)
2、#1的update操作,Query OK,匹配了2条并变更了2条。并且NO warnings; 这时候我们可能认为SQL执行正确。
![](https://image.xsoftlab.net/baike/articleImages/9bf873617bc6b2c60b6b5bcf5784e751.jpg)
再看select beijing表,id<=2 的uid=0 , 而gid 没有变化,显然不是我们想要的结果。
![](https://image.xsoftlab.net/baike/articleImages/bb4b37902c856dd41eebd312bab49fdb.jpg)
3、为什么会产生错误的结果呢? 我们看下面SQL,MySQL将“uid+1000 and gid=gid+1000”的值赋给了uid,“uid+1000 and gid=gid+1000”这个条件为假,MySQL中假即=0 ,从而导致了uid 赋值为0 而gid 并未更新。
![](https://image.xsoftlab.net/baike/articleImages/c5c2b5ad03e41ed4db96b2f0b53d7181.jpg)
4、正确的写法如#2 update beijing set uid=uid+1000 , gid=gid+1000 where id <=2 ;
![](https://image.xsoftlab.net/baike/articleImages/ccf3dd4fd5d38c897fac164bb66ce1dc.jpg)