where条件下mysql查询的一些现象

where条件下mysql查询的一些现象,mysql,char,Mysql,Char,有一张桌子 root@localhost:[test]05:35:05>desc t; +-----------+----------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------+----------+------+-----+---------+----------------+ | id

有一张桌子

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 |
+----+----------------------------------+
root@localhost:[测试]05:38:20>从t中选择*其中studio_id为0;
+----+----------------------------------+
|id |工作室id|
+----+----------------------------------+
|2 | 299a0be4a5a79e6a59fdd251b19d78bb|
+----+----------------------------------+

原因是mysql如何以静默方式将文本转换为数字,以计算number=text表达式,如mysql上的文档所述

Number=通过将两个操作数转换为浮点数来计算文本比较表达式

通过从左到右计算字符,将文本转换为数字。只要字符可以作为有效数字(符号、数字、小数点等)进行计算,mysql就会将其视为一个数字。当mysql遇到无法在数字中使用的字符(如字母)或将导致ivalid数字(如第二个符号)时,转换停止

文本
'foo1'
被转换为0,因为其最左边的字符是字母


文本
'299a0be4a5a79e6a59fdd251b19d78bb'
被转换为299,因为它以字符299开头,然后是字母
a
,不能解释为数字。

奇怪的是,当
foo1
具有id 2时,它返回id 2:这里有一个线索@11mb和草莓谢谢!让我知道你可以在线运行sql是的,你是对的。root@localhost:[test]06:59:07>从t中选择*,其中studio_id=299.00;+------------------------------------------------------------------------------------------+\124;id | studio | u id |+---------------------------------------------------------------------------------------------+| 2 | 299a0be4a5a79e6a59fdd251b19d78bb |+-----------------------------------------------------+但我无法理解您所说的“或将导致一个ivalid号码(如第二个符号)。”。这是什么意思?试试
选择'-123-1'+0
,你就会明白了。