有一桌,
root@localhost:[test]05:35:05>desc t;
+-----------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| studio_id | char(32) | YES | | NULL | |
+-----------+----------+------+-----+---------+----------------+
有两行:
root@localhost:[test]05:35:29>select * from t;
+----+----------------------------------+
| id | studio_id |
+----+----------------------------------+
| 1 | foo1 |
| 2 | 299a0be4a5a79e6a59fdd251b19d78bb |
+----+----------------------------------+
发现一些奇怪的查询现象,例如
# I can understand this
root@localhost:[test]05:37:00>select * from t where studio_id = '0';
Empty set (0.00 sec)
# I also understand this
root@localhost:[test]05:41:45>select * from t where studio_id = 1;
Empty set, 2 warnings (0.00 sec)
# but I can't understand this
root@localhost:[test]05:36:21>select * from t where studio_id = 0;
+----+-----------+
| id | studio_id |
+----+-----------+
| 1 | foo1 |
+----+-----------+
为什么可以返回记录,为什么只能返回foo1
回来了,怎么样299a0be4a5a79e6a59fdd251b19d78bb
?
root@localhost:[test]05:38:20>select * from t where studio_id <> 0;
+----+----------------------------------+
| id | studio_id |
+----+----------------------------------+
| 2 | 299a0be4a5a79e6a59fdd251b19d78bb |
+----+----------------------------------+
原因是 mysql 如何默默地将文本转换为数字以评估 number=text 表达式,如 mysql 文档中所述表达式求值中的类型转换 http://dev.mysql.com/doc/refman/5.7/en/type-conversion.html.
Number=text 比较表达式通过将两个操作数转换为浮点数来计算。
通过从左到右评估字符,将文本转换为数字。只要字符可以被评估为有效数字(符号,数字,小数点等),mysql就认为它是数字。当 mysql 遇到不能在数字中使用的字符(例如字母)或会导致无效数字(例如第二个符号)时,转换就会停止。
Text 'foo1'
被转换为 0,因为它最左边的字符是字母。
Text '299a0be4a5a79e6a59fdd251b19d78bb'
被转换为 299,因为它以字符 299 开头,然后是字母a
不能被解释为数字。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)