首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >mysql查询中的条件比较字符字段与int 0的一些现象

问mysql查询中的条件比较字符字段与int 0的一些现象
EN

Stack Overflow用户
提问于 2016-01-25 09:46:15
回答 1查看 64关注 0票数 1

有张桌子,

代码语言:javascript
复制
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    |                |
+-----------+----------+------+-----+---------+----------------+

有两行:

代码语言:javascript
复制
root@localhost:[test]05:35:29>select * from t;
+----+----------------------------------+
| id | studio_id                        |
+----+----------------------------------+
|  1 | foo1                             |
|  2 | 299a0be4a5a79e6a59fdd251b19d78bb |
+----+----------------------------------+

发现了一些奇怪的查询现象。

代码语言:javascript
复制
# 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呢?

代码语言:javascript
复制
root@localhost:[test]05:38:20>select * from t where studio_id <> 0;
+----+----------------------------------+
| id | studio_id                        |
+----+----------------------------------+
|  2 | 299a0be4a5a79e6a59fdd251b19d78bb |
+----+----------------------------------+
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-25 10:20:53

其原因是mysql如何悄悄地将文本转换为数字来计算number=text表达式,如mysql在表达式计算中的类型转换上的文档中所描述的那样。

Number=text比较表达式是通过将两个操作数转换为浮点数来计算的。

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

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34989411

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档