深入分析MySQL数据类型 DECIMAL

  # 创建具有DECIMAL字段的表 验证decimal默认是decimal(10,0)

  mysql> create table decimal_tb (col1 decimal,col2 decimal(5,2));

  Query OK, 0 rows affected (0.04 sec)

  mysql> show create table decimal_tbG

  *************************** 1. row ***************************

  Table: decimal_tb

  Create Table: CREATE TABLE `decimal_tb` (

  `col1` decimal(10,0) DEFAULT NULL,

  `col2` decimal(5,2) DEFAULT NULL

  ) ENGINE=InnoDB DEFAULT CHARSET=utf8

  1 row in set (0.00 sec)

  # 插入数据测试

  # 结论:超出存储范围会报错,小数位不足会自动补0,首位数字为0自动忽略,小数位超出会截断 并按四舍五入处理。

  mysql> insert into decimal_tb (col1,col2) values (100,100);

  Query OK, 1 row affected (0.05 sec)

  mysql> insert into decimal_tb (col2) values (1.23);

  Query OK, 1 row affected (0.01 sec)

  mysql> insert into decimal_tb (col2) values (10.2);

  Query OK, 1 row affected (0.01 sec)

  mysql> insert into decimal_tb (col2) values (09.9);

  Query OK, 1 row affected (0.01 sec)

  mysql> select * from decimal_tb;

  +------+--------+

  | col1 | col2 |

  +------+--------+

  | 100 | 100.00 |

  | NULL | 1.23 |

  | NULL | 10.20 |

  | NULL | 9.90 |

  +------+--------+

  4 rows in set (0.00 sec)

  mysql> insert into decimal_tb (col2) values (9999);

  ERROR 1264 (22003): Out of range value for column 'col2' at row 1

  mysql> insert into decimal_tb (col2) values (12.233);

  Query OK, 1 row affected, 1 warning (0.01 sec)

  mysql> show warnings;

  +-------+------+-------------------------------------------+

  | Level | Code | Message |

  +-------+------+-------------------------------------------+

  | Note | 1265 | Data truncated for column 'col2' at row 1 |

  +-------+------+-------------------------------------------+

  1 row in set (0.00 sec)

  mysql> insert into decimal_tb (col2) values (12.2300);

  Query OK, 1 row affected (0.01 sec)

  # 变量范围测试

  # 结论:M范围是1到65,D范围是0到30,且D不大于M

  mysql> alter table decimal_tb add column col3 decimal(6,6);

  Query OK, 0 rows affected (0.12 sec)

  Records: 0 Duplicates: 0 Warnings: 0

  mysql> alter table decimal_tb add column col4 decimal(6,7);

  ERROR 1427 (42000): For float(M,D), double(M,D) or decimal(M,D), M must be >= D (column 'col4').

  mysql> alter table decimal_tb add column col4 decimal(65,2);

  Query OK, 0 rows affected (0.11 sec)

  Records: 0 Duplicates: 0 Warnings: 0

  mysql> alter table decimal_tb add column col4 decimal(66,2);

  ERROR 1426 (42000): Too-big precision 66 specified for 'col4'. Maximum is 65.

  mysql> alter table decimal_tb add column col5 decimal(60,30);

  Query OK, 0 rows affected (0.13 sec)

  Records: 0 Duplicates: 0 Warnings: 0

  mysql> alter table decimal_tb add column col6 decimal(60,31);

  ERROR 1425 (42000): Too big scale 31 specified for column 'col6'. Maximum is 30.