update更新字段后,该字段值一直为 null,why?

业务同学反馈:

update 无效。更新 count 字段后,该字段一直为 null,非常奇怪!

Why?

生无可恋

场景重现

场景一:更新脚本执行后,字段未更新

mysql> update zilingzhi set count=count+1  where id=1;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1  Changed: 0  Warnings: 0

mysql> select * from zilingzhi;
+------+-------+
| id   | count |
+------+-------+
|    1 |  NULL |
|    2 |  NULL |
+------+-------+
2 rows in set (0.00 sec)

场景二:多更新几次,count 字段的值还是一直为 null

mysql> update zilingzhi set count=count+1  where id=1;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1  Changed: 0  Warnings: 0

mysql> update zilingzhi set count=count+1  where id=1;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1  Changed: 0  Warnings: 0

mysql> update zilingzhi set count=count+1  where id=1;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1  Changed: 0  Warnings: 0

mysql> select * from zilingzhi;
+------+-------+
| id   | count |
+------+-------+
|    1 |  NULL |
|    2 |  NULL |
+------+-------+
2 rows in set (0.00 sec)

这是为什么呢

查看表结构:

mysql> show create table zilingzhi;
+-----------+-----------------------------------------------------------------------------------------------------------------------------+
| Table     | Create Table                                                                                                                |
+-----------+-----------------------------------------------------------------------------------------------------------------------------+
| zilingzhi | CREATE TABLE `zilingzhi` (
  `id` int(11) DEFAULT NULL,
  `count` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+-----------+-----------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

count 字段默认值是 null.应该是在业务插入数据时,一开始未指定 count 字段内容,于是该字段内容一开始是 null.null 在 MySQL 中代表未知。

再来查一下 count+1 代表什么呢:

mysql> select count+1 from zilingzhi where id=1;
+---------+
| count+1 |
+---------+
|    NULL |
+---------+
1 row in set (0.01 sec)

原来如此。

所以,如果 count 列的初始值为 null 时,无论你 update zilingzhi set count=count+1 where id=1; 多少次,update 后 count 的值始终是 null.

怎么解决

方式一

字段尽量设置为 not null ,并带有默认值,比如 default 0 或 default ''。

(这其实是我们的开发规范喔)

方式二

利用函数 ifnull(count,0)

mysql> update zilingzhi set count=ifnull(count,0)+1 where id=1;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from zilingzhi ;
+------+-------+
| id   | count |
+------+-------+
|    1 |     1 |
|    2 |  NULL |
+------+-------+
2 rows in set (0.00 sec)

建议尽量用方式一解决。

开心脸

你可能感兴趣的:(update更新字段后,该字段值一直为 null,why?)