MySQL中字符串与数字比较

mysql> select 'abc'=0;
+---------+
| 'abc'=0 |
+---------+
|       1 |
+---------+
1 row in set, 1 warning (0.00 sec)
mysql> select '0abc'=0;
+----------+
| '0abc'=0 |
+----------+
|        1 |
+----------+
1 row in set, 1 warning (0.00 sec)
mysql> select '01abc'=0;
+-----------+
| '01abc'=0 |
+-----------+
|         0 |
+-----------+
1 row in set, 1 warning (0.00 sec)
mysql> select '013abc'=13;
+-------------+
| '013abc'=13 |
+-------------+
|           1 |
+-------------+
1 row in set, 1 warning (0.00 sec)

查阅MySQL 5.7官方文档中关于比较的章节,其中说明Strings are automatically converted to numbers and numbers to strings as necessary.。也就是说在比较的时候,String是可能会被转为数字的。

而对于数字开头的字符串来说,转为数字的结果就是截取前面的数字部分

mysql> select cast('123abc' as signed);
+-----------------------------+
| cast('123abc' as signed) |
+-----------------------------+
|                         123 |
+-----------------------------+
1 row in set, 1 warning (0.00 sec)
mysql> select cast('123.45abc' as decimal(5,2));
+-----------------------------------+
| cast('123.45abc' as decimal(5,2)) |
+-----------------------------------+
|                            123.45 |
+-----------------------------------+
1 row in set (0.00 sec)
mysql> select cast('abc' as signed);
+-----------------------+
| cast('abc' as signed) |
+-----------------------+
|                     0 |
+-----------------------+
1 row in set, 1 warning (0.00 sec)

```

而对于开头部分不能截取出数字的字符串来说,转换的结果自然就是0了。

关于字符串类型与整数直接进行比较的坑,说穿了就是MySQL中字符串转为数字的逻辑,没遇到过确实可能不太清楚,遇到过一次以后经验就是,看清楚数据库表字段,尽量避免字符串与数字的直接比较。

此外,书写sql语句的时候务必注意不要犯类型的错误,也许查出来的结果是对的,但是由于类型不匹配的原因,将会导致表索引无法用上

没有更多推荐了,返回首页