MySQL DECIMAL(x,0) 的范围是多少?
MySQL 中的 DECIMAL 类型用于存储精确数字,它支持以十进制形式存储数字,DECIMAL 的定义如下:
DECIMAL[(M[,D])]
其中 M 表示该数字的最大总位数,D 表示小数部分的位数。当 D 为 0 时,表示存储的是整数。在 MySQL 中,DECIMAL 类型的范围与存储所需空间有关。
下面分别讨论 DECIMAL(x,0) 的范围和存储空间。
阅读更多:MySQL 教程
范围
DECIMAL(x,0) 的取值范围为 -10^x+1 到 10^x-1。也就是说,x 决定了 DECIMAL(x,0) 所能存储的最大值和最小值,如下表所示:
| x | 最小值 | 最大值 |
|---|---|---|
| 1 | -9 | 9 |
| 2 | -99 | 99 |
| 3 | -999 | 999 |
| 4 | -9999 | 9999 |
我们可以通过下面的 SQL 语句进行验证:
CREATE TABLE decimal_test (x DECIMAL(3,0));
INSERT INTO decimal_test (x) VALUES (-999);
SELECT x FROM decimal_test; -- 输出:-999
INSERT INTO decimal_test (x) VALUES (999);
SELECT x FROM decimal_test; -- 输出:999
INSERT INTO decimal_test (x) VALUES (-1000); -- 报错:Out of range value for column 'x' at row 1
上面的 SQL 语句创建了一个 DECIMAL(3,0) 类型的列,并插入了两个值(-999 和 999)。发现数据被正确地存储和读取。当插入 -1000 时,MySQL 报错。
存储空间
DECIMAL 类型的存储空间取决于它的定义。在 MySQL 中,DECIMAL 类型被存储为定长字符串,需要的存储空间如下:
M / 9 + (M % 9 > 0) bytes
其中 M 是 DECIMAL(M,0) 的 M 值。以 DECIMAL(10,0) 为例,它的存储空间为:
10 / 9 + (10 % 9 > 0) = 2 bytes
我们可以通过下面的 SQL 语句进行验证:
CREATE TABLE decimal_size_test (
x DECIMAL(1,0),
y DECIMAL(9,0),
z DECIMAL(10,0),
u DECIMAL(19,0),
v DECIMAL(20,0)
);
SELECT table_name, column_name, data_type, character_maximum_length
FROM information_schema.columns
WHERE table_name = 'decimal_size_test';
-- 输出:
-- | table_name | column_name | data_type | character_maximum_length |
-- |-------------------|-------------|----------------|--------------------------|
-- | decimal_size_test | x | decimal | 1 |
-- | decimal_size_test | y | decimal | 9 |
-- | decimal_size_test | z | decimal | 10 |
-- | decimal_size_test | u | decimal | 19 |
-- | decimal_size_test | v | decimal | 20 |
上面的 SQL 语句创建了一个测试表,包含了不同位数的 DECIMAL 列。然后通过查询 information_schema.columns 系统表,查看每个列的数据类型和最大长度。输出结果显示 DECIMAL(1,0) 的长度为 1,DECIMAL(9,0) 的长度为 4,DECIMAL(10,0) 的长度为 6,依次类推。
结论
DECIMAL(x,0) 的取值范围为 -10^x+1 到 10^x-1,它的存储空间为 M / 9 + (M % 9 > 0) bytes,其中M 是 DECIMAL(M,0) 的 M 值。在使用 DECIMAL 类型时需要注意其范围和存储空间,以避免数据插入时的溢出和对存储空间的影响。
极客笔记