DECIMAL(M),允许实现决定M的值

DECIMAL(M), The Implementation Is Permitted to Decide the Value of M

文档指出,

In standard SQL, the syntax DECIMAL(M) is equivalent to DECIMAL(M,0). Similarly, the syntax DECIMAL is equivalent to DECIMAL(M,0), where the implementation is permitted to decide the value of M. MySQL supports both of these variant forms of DECIMAL syntax.

关于 DECIMAL(M)DECIMAL(M,0) 我感到困惑的部分是,

For DECIMAL(M,0), the implementation is permitted to decide the value of M.

如果列设置为 DECIMAL(65)4.321 将存储为 4,那么文档中的确切含义是什么?

通过 运行 这个测试在 MySQL 5.6:

create table t(
deci decimal, 
deci4 decimal(4),
deci40 decimal(4,0),
deci42 decimal(4,2)
);


insert into t(deci, deci4, deci40, deci42)
values
(1234.1234,1234.1234,1234.1234,1234.1234);

插入失败,因为 1234.1234 不适合 (4,2)

insert into t(deci, deci4, deci40, deci42)
values
(1234.1234,1234.1234,1234.1234,34.1234);

运行并插入以下值:

deci    deci4   deci40  deci42  
1234    1234    1234    34.12

DECIMAL(M,N)中,M是数字可以占的位数,包括小数点,N是小数点后的位数。 M 的最大值为 65,N 的最大值为 30。 N 必须小于 M。

如果N=00位小数。

如果不定义N,小数位数好像是按照整数部分实际占的位数来定义的,小于M的,剩下的位数留给小数根据需要。

如果两者均未定义,则 M 默认为 10

取自此处的有关默认值的信息: http://www.mysqltutorial.org/mysql-decimal/

换一种说法,使用 MySQL 选择的值:

  • DECIMAL 表示 DECIMAL(10,0)(占用 5 个字节)
  • DECIMAL(12) 表示 DECIMAL(12, 0)(其中“12”可以是不超过 65 的任何值)
  • 也就是说,无论是否明确说明,总有一个 M 和一个 N。

N0时,不存储小数。因此,4.321 将存储为 4。您可以存储的数字(没有四舍五入或截断)是小数点后不超过 N 位且小数点前不超过 M-N 位的数字。