如何在MySQL中正确划分两个DECIMAL值并获得精确到列类型中定义的位数的结果?
例:
select cast(1/2 as decimal(4,4)),
cast(1 as decimal(4,4))/2,
cast(1 as decimal(4,4))/cast(2 as decimal(4,4));
结果:
'0.5000', '0.49995000', '1.00000000'
为什么第二个结果是否真空?为什么第三个结果不是“0.5000”?
注意:我不能只使用第一个表单,我需要使用存储为小数的列执行计算.
解决方法:
问题是DECIMAL数据类型声明需要2个参数,第一个是总位数,包括小数部分.
根据文档(http://dev.mysql.com/doc/refman/5.7/en/precision-math-decimal-characteristics.html):
The declaration syntax for a DECIMAL column is DECIMAL(M,D). The
ranges of values for the arguments in MySQL 5.1 are as follows:M is the maximum number of digits (the precision). It has a range of 1
to 65. (Older versions of MySQL permitted a range of 1 to 254.)D is the number of digits to the right of the decimal point (the
scale). It has a range of 0 to 30 and must be no larger than M.
所以,如果你使用5位数而不是4位数,一切正常:
select cast(1/2 as decimal(5,4)),
cast(1 as decimal(5,4))/2,
cast(1 as decimal(5,4))/cast(2 as decimal(5,4)),
cast(cast(1 as decimal(5,4))/cast(2 as decimal(5,4)) as decimal(5,4));
结果
0.5000, 0.50000000, 0.50000000, 0.5000