[置顶] MySQL UPDATE语句中的一个诡异现象

给你一个很简单的语句,你能一眼看出语句的存在的问题么?

表结构如下:

CREATE TABLE `test_update` ( `id` int(11) DEFAULT NULL, `name` varchar(10) NOT NULL, `address` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8

表中数据如下:

mysql> select * from test_update; +------+---------+----------+
| id | name | address | +------+---------+----------+
|    1 | caoye   | shanghai |
|    2 | kezhu   | beijing  |
| 3 | yanzhao | luoyang | +------+---------+----------+
3 rows in set (0.02 sec)

我要说的SQL如下:

UPDATE test_update SET NAME = '123' AND address = "ShangHai" WHERE id = 1;

有问题么???不知大家有没看出来,我第一次执行开发提交过来的类似这么一条语句前根本没有发现问题。执行完发生了诡异现象才意识到问题所在。

对的,UPDATE中更新多个字段时中字段间不是用AND而是要用”,”,但用AND时MySQL居然不报语法错误,而只在一定条件下报类型错误,多数情况下什么错误都没有,只是结果看起来比较异常。

不妨通过例子来看看:

mysql> update test_update set name='CaoYe' and address="ShangHai" where id=1; ERROR 1292 (22007): Truncated incorrect DOUBLE value: 'CaoYe' mysql> update test_update set name='123' and address="ShangHai" where id=1; Query OK, 1 row affected (0.01 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select * from test_update; +------+---------+----------+
| id | name | address | +------+---------+----------+
|    1 | 1       | shanghai |
|    2 | kezhu   | beijing  |
| 3 | yanzhao | luoyang | +------+---------+----------+

值发生了更新,但是name神奇的变成了1,address没有发生变化。

mysql> update test_update set name='234' and address="456" where id=1; Query OK, 1 row affected (0.02 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select * from test_update; +------+---------+----------+
| id | name | address | +------+---------+----------+
|    1 | 0       | shanghai |
|    2 | kezhu   | beijing  |
| 3 | yanzhao | luoyang | +------+---------+----------+
3 rows in set (0.02 sec)

值发生了变化,但这次name神奇的变为了0,address没有变化。

mysql> update test_update set name=345 and address=678 where id=3;
ERROR 1292 (22007): Truncated incorrect DOUBLE value: 'luoyang'

当把address试图写成整型时报错

mysql> update test_update set name=345 and address="678" where id=3; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select * from test_update; +------+------+----------+
| id | name | address | +------+------+----------+
|    1 | 0    | shanghai |
|    2 | 0    | beijing  |
| 3 | 0 | luoyang | +------+------+----------+
3 rows in set (0.01 sec)

重新恢复address为字符串型是又可执行成功,且name变成了0

真是太诡异了,以后使用UPDATE语句是一定要注意。一个符号之差,造成十分危险的后果。

你可能感兴趣的:(sql,mysql,update)