【问题标题】:some phenomenon of mysql query in where condition compare char filed with int 0mysql查询where条件比较char字段与int 0的一些现象
【发布时间】:2016-01-25 09:46:15
【问题描述】:

有一张桌子,

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      |
+----+-----------+

为什么会返回记录,为什么只返回foo1299a0be4a5a79e6a59fdd251b19d78bb 呢?

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

【问题讨论】:

标签: mysql char


【解决方案1】:

原因是 mysql 如何静默地将文本转换为数字以评估 number=text 表达式,如 mysql 在type conversion in expression evaluation 上的文档中所述。

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

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

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

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

【讨论】:

  • 是的,你是对的。 root@localhost:[test]06:59:07>select * from t where studio_id = 299.00; +----+----------------------------------+ |编号 |工作室 ID | +----+----------------------------------+ | 2 | 299a0be4a5a79e6a59fdd251b19d78bb | +----+------------------------------------------------+
  • 但我无法理解您所说的“或者会导致有效的数字(例如第二个符号)。” .什么意思?
  • 试试Select '-123-1'+0你就会明白了。
猜你喜欢
  • 1970-01-01
  • 2018-06-24
  • 1970-01-01
  • 1970-01-01
  • 2010-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多