Update时逗号和and的区别

2020-05-03  本文已影响0人  丿灬尘埃

相信MySQL新老玩家一定知道正确的update怎么操作吧!
ok!
展现下作者并不是什么都不会的小白
是时候表现一波真正的技术了,update来了

update table set  a = `a0` and b = `b0`  where  c = `c`;

是不是很简单?
如果你看不出任何问题,那么少年你还太年轻,去把w3c或者其他的mysql自己默默的去看一遍。
别怪我没提醒你哦!出了问题回滚都很麻烦。
好了,看下正确的写法吧

update table set  a = `a0` , b = `b0`  where  c = `c0`;

不知道屏幕前的你,是否看出了这真假update的问题呢?
没错就是一个逗号和一个and符的区别,那么二者对于数据有什么影响呢?
上荔枝:
数据库已经创建,数据如下:

MySQL [test_db]> select * from test;
+----+-----+--------+-------+-------+
| id | age | name   | class | uk_id |
+----+-----+--------+-------+-------+
|  1 |  14 | 小明   | 1     |     1 |
|  2 |  19 | 小     | 2     |     2 |
+----+-----+--------+-------+-------+
2 rows in set (0.00 sec)

ok!
来一波and更新,更新
age 全部更为 18 姓名更新为 王明 uk_id 更新为 99 没有条件的更新(尽管不推荐没有条件更新,但是为了测试就先忽略吧)
如果咱们的SQL语句是update test set age = 18 and name = '王明' and uk_id =99; 会发生什么呢?
看结果吧:

MySQL [test_db]> update test set age = 18 and name = '王明' and uk_id =99;
Query OK, 2 rows affected (0.08 sec)
Rows matched: 2  Changed: 2  Warnings: 0
+----+-----+--------+-------+-------+
| id | age | name   | class | uk_id |
+----+-----+--------+-------+-------+
|  1 |   0 | 小明   | 1     |     1 |
|  2 |   0 | 小     | 2     |     2 |
+----+-----+--------+-------+-------+

是不是很意外,只是更新了age列,且结果都是0,什么原因呢?
是不是猜到后面那一坨进行了什么见不得人的运算呢,猜对了,后面进行了逻辑运算。
其实这句SQL的真正含义是:把 name = '王明' 并且 uk_id =99 的数据age更新为1 ,其余数据更新为0
什么不信,来在测试下,看法宝:

MySQL [test_db]> update test set age = 18 and name = '小明' and uk_id =1;
Query OK, 1 row affected (0.04 sec)
Rows matched: 2  Changed: 1  Warnings: 0

这句sql,会把 name = '小明' and uk_id =1的age更新为1 否则更新为0,
所以id=1 的 age= 1 , id =2 的 age=0
看结果吧

MySQL [test_db]> update test set age = 18 and name = '小明' and uk_id =99;
Query OK, 0 rows affected (0.01 sec)
Rows matched: 2  Changed: 0  Warnings: 0

MySQL [test_db]> select * from test;
+----+-----+--------+-------+-------+
| id | age | name   | class | uk_id |
+----+-----+--------+-------+-------+
|  1 |   0 | 小明   | 1     |     1 |
|  2 |   0 | 小     | 2     |     2 |
+----+-----+--------+-------+-------+
2 rows in set (0.00 sec)

MySQL [test_db]> update test set age = 18 and name = '小明' and uk_id =1;
Query OK, 1 row affected (0.04 sec)
Rows matched: 2  Changed: 1  Warnings: 0

MySQL [test_db]> select * from test;
+----+-----+--------+-------+-------+
| id | age | name   | class | uk_id |
+----+-----+--------+-------+-------+
|  1 |   1 | 小明   | 1     |     1 |
|  2 |   0 | 小     | 2     |     2 |
+----+-----+--------+-------+-------+
2 rows in set (0.00 sec)

所以明白逗号和and的区别了吧,更新需谨慎,SQL不规范,修复之人泪两行。
正确的MYSQL update 语句相信你应该知道的,so就不在提醒了,什么需要提醒?
好吧,update 出来吧

update table set  a = `a0` , b = `b0`  where  c = `c0`;
上一篇 下一篇

猜你喜欢

热点阅读