int最大存储
无符号数
int使用4个字节存储,每个字节8个比特位,存储最大数据为2的32次方减1
-- 4294967296 = 2的32次方
-- 修改test字段为int 无符号位
alter table account3 modify column test int(10) unsigned null comment '测试 int max';
update account3 set test = 4294967296 where id = 2;
ERROR 1264 (22003): Out of range value for column 'test' at row 1
update account3 set test = 4294967295 where id = 2;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
有符号数
但是很多场景下使用int类型的字段存储负数,需要去掉无符号标记unsigned。这时int的32的比特位只有31个标识数据存储,剩余的一个标识符号位(正,负),这时int的取值变成负2的31次方 ~ 正2的31次方减1
-- 2147483648 = 2的31次方
-- 无符号位设置为负数失败
update account3 set test = -1 where id = 2;
ERROR 1264 (22003): Out of range value for column 'test' at row 1
-- 修改test字段为int 有符号位
alter table account3 modify column test int(10) null comment '测试 int max';
-- 有符号位正数能够设置为2的31次方减1
update account3 set test = 2147483648 where id = 2;
ERROR 1264 (22003): Out of range value for column 'test' at row 1
update account3 set test = 2147483647 where id = 2;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1 Changed: 0 Warnings: 0
-- 有符号位负数能够设置为2的31次方
update account3 set test = -2147483649 where id = 2;
ERROR 1264 (22003): Out of range value for column 'test' at row 1
update account3 set test = -2147483648 where id = 2;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
有符号位 -2的31次方 ~ 2的31次方减1,无符号位 0 ~ 2的32次方减1
为什么负数能够多表示一位
计算机使用补码表示和存储数值,补码的0只有一个且最小负数的补码恰好符合1000
篇幅较多参考这里
int(11)的意义
通过上面的分析int最多能够存储的数字长度是10位(4294967295 和 2147483647),但是实际使用中字段类型会被设置为int(11)。其实int(X)后面的数字并不是int存储的限制位,而是配合zerofill使用,达到零填充显示的功能
-- 修改为zerofill
alter table account3 modify column test int(3) zerofill null comment '测试 int max';
Query OK, 0 rows affected, 2 warnings (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 2
-- 查询12不足int(3)时,高位零填充
select test from account3;
+--------+
| test |
+--------+
| 123456 |
| 012 |
+--------+
2 rows in set (0.00 sec)
-- zerofill的字段不能设置为负数
update account3 set test = -1 where id = 2;
ERROR 1264 (22003): Out of range value for column 'test' at row 1
- zerofill会将字段变成无符号位
- 需要存储更大的数据使用类型 bigint
由上,int(5) 和 int(10)的区别在于零填充的数量不同
欢迎大家留言交流讨论,如果对你有帮助,请点个赞吧