Mysql中 float double decimal 列的等值查詢

原文鏈接: Mysql中float列的等值查詢

注:float 類型的數據在比較相等時,無論是在c,c++,java,php 等語言比較時,都需要特別注意。

 

mysql中float類型不定義精度時,對float列的檢索可能不正確。即如果有記錄存在 field_float_a 值爲1.234, 查詢select * from table_test where field_float_a  = 1.234. 可能查詢不到數據。

 

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

---------------------
作者:lwei_998
來源:CSDN
原文:https://blog.csdn.net/lwei_998/article/details/40979351
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章