当我使用数字类型选择varchar列时会发生什么?

nbewdwxp  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(283)

我有一张table:

CREATE TABLE `test` (
  `t` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8

表中数据为:

mysql> select * from test;

+----------------------+
| t                    |
+----------------------+
| 12511023900355495873 |
| 12511023900355495872 |
| 12511023900355495874 |
+----------------------+

当我 select 从下面的表格中:

select * from test where t = 12511023900355495873;

结果是:

+----------------------+
| t                    |
+----------------------+
| 12511023900355495873 |
| 12511023900355495872 |
| 12511023900355495874 |
+----------------------+

当我使用 number 选择一个 varchar 列?

carvr3hs

carvr3hs1#

手册页https://dev.mysql.com/doc/refman/5.7/en/type-conversion.html 在所有其他情况下,参数作为浮点数(实数)进行比较。
所以

drop table if exists t;

CREATE TABLE t (

t varchar(255) DEFAULT NULL,
t1 float

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into t values
( 12511023900355495873,12511023900355495873 ),
( 12511023900355495872,12511023900355495872 ),
( 12511023900355495874,12511023900355495874 );

select t.*,@t2 from t where t = 12511023900355495873;

结果

+----------------------+-----------+------+
| t                    | t1        | @t2  |
+----------------------+-----------+------+
| 12511023900355495873 | 1.2511e19 | NULL |
| 12511023900355495872 | 1.2511e19 | NULL |
| 12511023900355495874 | 1.2511e19 | NULL |
+----------------------+-----------+------+
3 rows in set (0.00 sec)

请注意,t1列中的所有浮点值都是相同的。
不用说,你应该避免类型转换。

相关问题