2016-01-25 30 views
1

有一个表申请,在条件比较焦炭MySQL查询的一些现象与诠释0

[email protected]:[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 |    | 
+-----------+----------+------+-----+---------+----------------+ 

有两行:

[email protected]:[test]05:35:29>select * from t; 
+----+----------------------------------+ 
| id | studio_id      | 
+----+----------------------------------+ 
| 1 | foo1        | 
| 2 | 299a0be4a5a79e6a59fdd251b19d78bb | 
+----+----------------------------------+ 

发现了一些奇怪的现象查询,例如

# I can understand this 
[email protected]:[test]05:37:00>select * from t where studio_id = '0'; 
Empty set (0.00 sec) 
# I also understand this 
[email protected]:[test]05:41:45>select * from t where studio_id = 1; 
Empty set, 2 warnings (0.00 sec) 


# but I can't understand this 
[email protected]:[test]05:36:21>select * from t where studio_id = 0; 
+----+-----------+ 
| id | studio_id | 
+----+-----------+ 
| 1 | foo1  | 
+----+-----------+ 

为什么可能返回的记录,为什么只有foo1回来,那299a0be4a5a79e6a59fdd251b19d78bb

[email protected]:[test]05:38:20>select * from t where studio_id <> 0; 
+----+----------------------------------+ 
| id | studio_id      | 
+----+----------------------------------+ 
| 2 | 299a0be4a5a79e6a59fdd251b19d78bb | 
+----+----------------------------------+ 
+0

奇怪的是,当'foo1'有id时,它返回id 2 2:http://sqlfiddle.com/#!9/8f8a7/1 – 11mb

+0

这是一个线索...... http://sqlfiddle.com/# !9/8f8a7/5 – Strawberry

+1

@ 11mb和草莓谢谢!让我知道可以在线运行sql – zhuguowei

回答

0

原因是MySQL如何默默地将文本转换为数字作为上type conversion in expression evaluation MySQL的文档中描述,以评估数=文本表达。

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

通过评估从左到右的字符将文本转换为数字。只要字符可以被评估为一个有效的数字(符号,数字,小数点等),mysql会将其视为一个数字。当mysql遇到不能在数字中使用的字符(例如字母)或者导致ivalid数字(如第二个符号)时,转换将停止。

将文本'foo1'转换为0,因为它的最左侧字符是字母。

将文本'299a0be4a5a79e6a59fdd251b19d78bb'转换为299,因为它以字符299开始,然后出现不能被解释为数字的字母a

+0

是的,你是对的。 root @ localhost:[test] 06:59:07> select * from t where studio_id = 299.00; + ---- + ---------------------------------- + | id | studio_id | + ---- + ---------------------------------- + | 2 | 299a0be4a5a79e6a59fdd251b19d78bb | + ---- + ---------------------------------- + – zhuguowei

+0

但我无法理解你说“或将导致一个无效号码(如第二个标志)。” 。什么意思? – zhuguowei

+0

尝试'选择'-123-1'+ 0',你就会明白。 – Shadow