【mysql】int最多能够存储10位,为什么会有int11

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)的区别在于零填充的数量不同

欢迎大家留言交流讨论,如果对你有帮助,请点个赞吧

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值