困惑最近遇到个问题,有个表的要加个user_id字段,user_id字段可能很大,于是我提mysql工单alter table xxx add user_id int(1)。在看到我的sql工单后,领导说道:恐怕你所设定的int(1)可能不够使用,接着开始进行解释。
我并不是第一次遇到这种问题,有些遇到过这种问题的人已经从事这个工作超过5年。包括我经常在也看到同事也一直使用int(10),感觉用了int(1),字段的上限就被限制,真实情况肯定不是这样。
数据说话我们知道在mysql中 int占4个字节,那么对于无符号的int,最大值是2^32-1 = 4294967295,将近40亿,难道用了int(1),就不能达到这个最大值吗?
create table `user` ( `id` int(1) unsigned not null auto_increment, primary key (`id`)) engine=innodb auto_increment=1 default charset=utf8mb4;
id字段为无符号的int(1),我来插入一个最大值看看。
mysql> insert into `user` (`id`) values (4294967295);query ok, 1 row affected (0.00 sec)
可以看到成功了,说明int后面的数字,不影响int本身支持的大小,int(1)、int(2)...int(10)没什么区别。
零填充一般int后面的数字,配合zerofill一起使用才有效。先看个例子:
create table `user` ( `id` int(4) unsigned zerofill not null auto_increment, primary key (`id`)) engine=innodb auto_increment=1 default charset=utf8mb4;
注意int(4)后面加了个zerofill,我们先来插入4条数据。
mysql> insert into `user` (`id`) values (1),(10),(100),(1000);query ok, 4 rows affected (0.00 sec)records: 4 duplicates: 0 warnings: 0
分别插入1、10、100、1000 4条数据,然后我们来查询下:
mysql> select * from user;+------+| id |+------+| 0001 || 0010 || 0100 || 1000 |+------+4 rows in set (0.00 sec)
通过数据可以发现 int(4) + zerofill实现了不足4位补0的现象,单单int(4)是没有用的。
而且对于0001这种,底层存储的还是1,只是在展示的会补0。
以上就是mysql中int(1)和int(10)有哪些区别的详细内容。