评“MySQL 隐式转换引起的执行结果错误”

来源:这里教程网 时间:2026-03-01 12:09:54 作者:

今天看到一篇关于MySQL隐式转换引发执行结果错误的文章:===========================================================================

今天给大家,带来的例子是 MySQL Join过程中发生隐式转换导致结果跟预期的不一样的问题。

下面是 即将使用的表和插入数据的 脚本

create table a (nntx_no int ) ;
create table b (nntx_no varchar(20) ) ;
root@mysql3306.sock>[test]>insert into a values (1772 ) ;
Query OK, 1 row affected (0.00 sec)
root@mysql3306.sock>[test]>insert into a values (1773 ) ;
Query OK, 1 row affected (0.00 sec)
root@mysql3306.sock>[test]>insert into b values ('1772' ) ;
Query OK, 1 row affected (0.00 sec)
root@mysql3306.sock>[test]>insert into b values ('1772.0 ~ 34' ) ;
Query OK, 1 row affected (0.01 sec)

下面是表数据

root@mysql3306.sock>[test]>select * from a ;
+---------+
| nntx_no |
+---------+
| 1772 |
| 1773 |
+---------+
2 rows in set (0.00 sec)
root@mysql3306.sock>[test]>select * from b ;
+-------------+
| nntx_no |
+-------------+
| 1772 |
| 1772.0 ~ 34 |
+-------------+
2 rows in set (0.00 sec)

运行如下SQL

select a.nntx_no, b.nntx_no
 -> from a
 -> left join b on a.nntx_no = b.nntx_no
 -> where 1=1
 -> and a.nntx_no = 1772;
+---------+-------------+
| nntx_no | nntx_no |
+---------+-------------+
| 1772 | 1772 |
| 1772 | 1772.0 ~ 34 |
+---------+-------------+

可以看到出了 两行数据,但是其中第二行数据 显然不符合我们的预期

但MySQL却给我们了一个看似错误的结果!!!

现在我们来分析,这个结果的原因

root@mysql3306.sock>[test]>select a.nntx_no, b.nntx_no
 -> from a
 -> left join b on a.nntx_no = b.nntx_no
 -> where 1=1
 -> and a.nntx_no = 1772;
+---------+-------------+
| nntx_no | nntx_no |
+---------+-------------+
| 1772 | 1772 |
| 1772 | 1772.0 ~ 34 |
+---------+-------------+
2 rows in set, 2 warnings (0.00 sec)
root@mysql3306.sock>[test]>show warningsG
*************************** 1. row ***************************
 Level: Warning
 Code: 1292
Message: Truncated incorrect DOUBLE value: '1772.0 ~ 34'
*************************** 2. row ***************************
 Level: Warning
 Code: 1292
Message: Truncated incorrect DOUBLE value: '1772.0 ~ 34'
2 rows in set (0.00 sec)

从show warnings 中 可以看出一些端倪 有两个warning

显示 Truncated incorrect DOUBLE value: '1772.0 ~ 34'

说明 '1772.0 ~ 34' 转换过程中,被截断了

我们坐下如下实验

root@mysql3306.sock>[test]>select '1772.0 ~ 34' + 0 ;
+-------------------+
| '1772.0 ~ 34' + 0 |
+-------------------+
| 1772 |
+-------------------+

说明 '1772.0 ~ 34' 字符串转换成数字的过程中 被转换成1772 所以MySQL 给我们

得出了上面的结果!

那原因,已经知道了 剩下的就是怎样处理了!

我们从上面的结果中已经知道,原因是字符串变成数字的过程中被截取导致的,

那解决方案就是,不进行数字类型转换就可以了。

如下所示,用了 concat(a.nntx_no,'') 使数字类型变成字符串类型,从而字符串=字符串

这样就可以了 !!!

root@mysql3306.sock>[test]>select a.nntx_no, b.nntx_no
 -> from a
 -> left join b on concat(a.nntx_no,'') = b.nntx_no
 -> where 1=1
 -> and a.nntx_no = 1772;
+---------+---------+
| nntx_no | nntx_no |
+---------+---------+
| 1772 | 1772 |
+---------+---------+
1 row in set (0.00 sec)

以上就是,今天的内容===========================================================================这应该算了MySQL的一个Bug吧。 1、从CHAR到INT的转换,不成功应该要报错; 2、隐式转换,应该要保持数据不丢失,即从INT到CHAR的转换;

相关推荐