MySQL 是 5.7.23。
IFNULL(INET_ATON(''),0)
在普通选择中返回 0,但在 update ... set
赋值期间返回 ERRORS
问:是否有补丁可以防止 ERROR 1411 (HY000): Incorrect string value:
更新语句由较大的应用程序生成,很难修改应用程序。
mysql> create table foo (id int not null, ip int not null);
Query OK, 0 rows affected (0.21 sec)
mysql> insert into foo values (0,0);
Query OK, 1 row affected (0.26 sec)
更新成功,真实ip字符串
mysql> update foo set ip = ifnull(inet_aton('10.10.10.254'), 0) where id=0;
Query OK, 1 row affected (0.25 sec)
Rows matched: 1 Changed: 1 Warnings: 0
带 IFNULL 的普通选择得到所需的 0
mysql> select IFNULL(inet_aton(''),0);
+-------------------------+
| IFNULL(inet_aton(''),0) |
+-------------------------+
| 0 |
+-------------------------+
1 row in set, 1 warning (0.00 sec)
更新失败,IFNULL 和 INET_ATON 的空 ip 字符串
mysql> update foo set ip = ifnull(inet_aton(''), 0) where id=0;
ERROR 1411 (HY000): Incorrect string value: '''' for function inet_aton
更新失败,IFNULL 和 INET_ATON 的 IPv6 环回地址
mysql> update foo set ip = ifnull(inet_aton('::1'), 0) where id=0;
ERROR 1411 (HY000): Incorrect string value: ''::1'' for function inet_aton
最佳答案
事实上,空字符串在这两种情况下都是无效参数。查看warnings可以看到是warning:
mysql> warnings;
Show warnings enabled.
mysql> select IFNULL(inet_aton(''),0);
+-------------------------+
| IFNULL(inet_aton(''),0) |
+-------------------------+
| 0 |
+-------------------------+
1 row in set, 1 warning (0.00 sec)
Warning (Code 1411): Incorrect string value: '''' for function inet_aton
我不确定为什么这只是在使用 SELECT 时出现警告,而在 UPDATE 中使用相同函数时出现错误。
解决方法是使用 NULL 而不是空白字符串。如果您将 NULL 作为您的 IP 地址字符串传递,INET_ATON() 将返回 NULL 而不会发出警告或错误:
mysql> update foo set ip = ifnull(inet_aton(''), 0) where id=0;
ERROR 1411 (HY000): Incorrect string value: '''' for function inet_aton
mysql> update foo set ip = ifnull(inet_aton(null), 0) where id=0;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
我知道您说过很难更改应用程序,但这是我可以建议的唯一解决方法。
当然,最好的解决方案是避免将任何无效字符串传递给 INET_ATON()。
关于更新期间出现 MySQL INET_ATON 错误,消息为 "Incorrect string value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55210574/