Mysql中float列的等值查询

mysql中float类型不定义精度时,对float列的检索可能不正确。

 

1.创建表t3,col1_float定义为float类型不指定精度
mysql> CREATE TABLE `t3` (
  `col1_float` float DEFAULT NULL,
  `col2_double` double DEFAULT NULL,
  `col3_decimal` decimal DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
Query OK, 0 rows affected

 

2.插入数据
mysql中float类型不指定精度时,会按照实际的精度显示
mysql> insert into t3 values(100.123,200.123,300.123);
Query OK, 1 row affected

mysql> select * from t3;
+------------+-------------+--------------+
| col1_float | col2_double | col3_decimal |
+------------+-------------+--------------+
|    100.123 |     200.123 | 300          |
+------------+-------------+--------------+
1 row in set

 

3.对float类型不指定精度时,默认等值查询结果为空.

如t3表中存在col1_float为100.123的记录,但由于定义col1_float的类型时没有指定float的精度,在对float列进行等值查询的时候检索不到记录。


mysql> select * from t3 where col1_float=100.123;
Empty set

mysql> show warnings;
Empty set


4.对double类型,则没有这种情况
mysql> select * from t3 where col2_double=200.123;
+------------+-------------+--------------+
| col1_float | col2_double | col3_decimal |
+------------+-------------+--------------+
|    100.123 |     200.123 | 300          |
+------------+-------------+--------------+
1 row in set

 

4.对decimal类型,如果不指定精度, 会对小数位进行截断
mysql> select * from t3 where col3_decimal=300;
+------------+-------------+--------------+
| col1_float | col2_double | col3_decimal |
+------------+-------------+--------------+
|    100.123 |     200.123 | 300          |
+------------+-------------+--------------+
1 row in set


Mysql中针对不定义精度的float类型进行等值查询的解决方法:

a).使用like
mysql> select * from t3 where col1_float like 100.123;
+------------+-------------+--------------+
| col1_float | col2_double | col3_decimal |
+------------+-------------+--------------+
|    100.123 |     200.123 | 300          |
+------------+-------------+--------------+
1 row in set

b).使用format进行转换
mysql> select * from t3 where format(col1_float ,3) = format(100.123 ,3);
+------------+-------------+--------------+
| col1_float | col2_double | col3_decimal |
+------------+-------------+--------------+
|    100.123 |     200.123 | 300          |
+------------+-------------+--------------+
1 row in set

c). 修改数据类型,指定精度和标度。
mysql> alter table t3 modify col1_float  float(6,3);
Query OK, 0 rows affected
Records: 0  Duplicates: 0  Warnings: 0

mysql> select * from t3 where col1_float=100.123;
+------------+-------------+--------------+
| col1_float | col2_double | col3_decimal |
+------------+-------------+--------------+
|    100.123 |     200.123 | 300          |
+------------+-------------+--------------+
1 row in set

你可能感兴趣的:(Mysql中float列的等值查询)