有张桌子,
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 |
+----+----------------------------------+发布于 2016-01-25 10:20:53
其原因是mysql如何悄悄地将文本转换为数字来计算number=text表达式,如mysql在表达式计算中的类型转换上的文档中所描述的那样。
Number=text比较表达式是通过将两个操作数转换为浮点数来计算的。
通过计算从左到右的字符,将文本转换为数字。只要可以将字符计算为有效数字(符号、数字、小数点等),mysql就将其视为一个数字。当mysql遇到一个不能在数字(例如字母)中使用的字符时,转换就停止了,或者会产生一个有效的数字(例如第二个符号)。
文本'foo1'被转换为0,因为其最左边的字符是一个字母。
文本'299a0be4a5a79e6a59fdd251b19d78bb'被转换为299,因为它以字符299开头,然后是不能解释为数字的字母a。
https://stackoverflow.com/questions/34989411
复制相似问题