­

【坑】 MySQL中,字符串和数值的比较

  • 2019 年 10 月 4 日
  • 筆記

官方文档:https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html

原文:

Comparison operations result in a value of 1 (TRUE), 0 (FALSE), or NULL. These operations work for both numbers and strings. Strings are automatically converted to numbers and numbers to strings as necessary.

也就是说在比较的时候,String是可能会被转为数字的。

对于数据开头的字符串,转成数字后会自动丢弃后面的字母部分,只留下纯数字进行比较。

对于没有数字的那些字符串,与数值进行比较的时候,就只剩下0去和其他数值进行比较了。

例子:

1、对于没有数字的那些字符串,与数值进行比较的时候,就只剩下0去和其他数值进行比较了。:

root [(none)] >select 0='abc';  +---------+  | 0='abc' |  +---------+  |       1 |  +---------+  1 row in set, 1 warning (0.00 sec)  root [(none)] >show warnings;  +---------+------+-----------------------------------------+  | Level   | Code | Message                                 |  +---------+------+-----------------------------------------+  | Warning | 1292 | Truncated incorrect DOUBLE value: 'abc' |  +---------+------+-----------------------------------------+

1 row in set (0.00 sec)

2、对于数据开头的字符串,转成数字后会自动丢弃后面的字母部分,只留下纯数字进行比较。

root [(none)] >select 11='010abc';  +-------------+  | 11='010abc' |  +-------------+  |           0 |  +-------------+  1 row in set, 1 warning (0.00 sec)  root [(none)] >show warnings;  +---------+------+--------------------------------------------+  | Level   | Code | Message                                    |  +---------+------+--------------------------------------------+  | Warning | 1292 | Truncated incorrect DOUBLE value: '010abc' |  +---------+------+--------------------------------------------+

1 row in set (0.00 sec)

官方网站给的例子更多,更多感兴趣的可以去看看。

其实字符串和数值比较最大的坑在于:它会导致查询不能用到索引,直接就影响了查询的效率。