MySQL文档中的示例http://dev.mysql.com/doc/refman/5.1/en/problems-with-float.html(我将其缩小,本节的文档与5.5相同)
mysql> create table t1 (i int, d1 double, d2 double);
mysql> insert into t1 values (2, 0.00 , 0.00),
(2, -13.20, 0.00),
(2, 59.60 , 46.40),
(2, 30.40 , 30.40);
mysql> select
i,
sum(d1) as a,
sum(d2) as b
from
t1
group by
i
having a <> b;
+
| i | a | b |
+
| 2 | 76.80000000000001 | 76.8 |
+
1 row in set (0.00 sec)
基本上,如果您求和a,您将得到0-13.2 + 59.6 + 30.4 = 76.8。如果将b求和,则得到0 + 0 + 46.4 + 30.4 = 76.8。a和b的总和是相同的,但是MySQL文档说:
SQL语句中编写的浮点值可能与内部表示的值不同。
如果我们用十进制重复相同的内容:
mysql> create table t2 (i int, d1 decimal(60,30), d2 decimal(60,30));
Query OK, 0 rows affected (0.09 sec)
mysql> insert into t2 values (2, 0.00 , 0.00),
(2, -13.20, 0.00),
(2, 59.60 , 46.40),
(2, 30.40 , 30.40);
Query OK, 4 rows affected (0.07 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select
i,
sum(d1) as a,
sum(d2) as b
from
t2
group by
i
having a <> b;
Empty set (0.00 sec)
预期结果为空集。
因此,只要您不执行任何SQL算术运算,就可以使用DOUBLE,但我还是希望DECIMAL。
关于小数位数要注意的另一件事是,如果小数部分太大,则四舍五入。例:
mysql> create table t3 (d decimal(5,2));
Query OK, 0 rows affected (0.07 sec)
mysql> insert into t3 (d) values(34.432);
Query OK, 1 row affected, 1 warning (0.10 sec)
mysql> show warnings;
+
| Level | Code | Message |
+
| Note | 1265 | Data truncated for column 'd' at row 1 |
+
1 row in set (0.00 sec)
mysql> select * from t3;
+
| d |
+
| 34.43 |
+
1 row in set (0.00 sec)