先看下官网的说法:
MySQL supports an extension for optionally specifying the display width of integer data types in parentheses following the base keyword for the type. For example, INT(4) specifies an INT with a display width of four digits. This optional display width may be used by applications to display integer values having a width less than the width specified for the column by left-padding them with spaces. (That is, this width is present in the metadata returned with result sets. Whether it is used is up to the application.)
关键信息:int(n)中的n,是个可选设置(optionally),它指示了数字的显示宽度(display width of integer data type).
至于怎么理解显示宽度?
n决定了当数字的宽度小于n时,mysql会在数值的左边填充空格(by left-padding them with spaces)。并不意味着列的值包含的数字个数不能超过n,这一点跟varchar(n)中n的含义不同。
我们看下varchar(n)的含义。
mysql> insert into a_test(id,name) values (2,'123456');
Query OK, 1 row affected, 1 warning (0.00 sec)
mysql> select * from a_test;
+----+--------+-------+
| id | age | name |
+----+--------+-------+
| 1 | 123456 | NULL |
| 2 | NULL | 12345 |
+----+--------+-------+
2 rows in set (0.00 sec)
可以看到,name只存储了5个字符长度,varchar(n)中的n是指字符串长度(字符个数)。
我们验证下int(n)类型能否存储超过n个数字的值。
CREATE TABLE `a_test` (
`id` bigint NOT NULL AUTO_INCREMENT,
`age` int(5) DEFAULT NULL,
`name` varchar(5) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
mysql> insert into a_test(id, age) values
-> (1,123456);
Query OK, 1 row affected (0.01 sec)
mysql> select * from a_test;
+----+--------+------+
| id | age | name |
+----+--------+------+
| 1 | 123456 | NULL |
+----+--------+------+
1 row in set (0.00 sec)
显然成功了。事实上我们也知道int类型能存储的值范围:-2,147,483,648~2,147,483,647。
存储大小为 4 个字节。可以存储从 -2^31 (-2,147,483,648) 到 2^31 - 1 (2,147,483,647) 的整型数据。
因为当数字的宽度小于n时,mysql会在数值的左边填充空格(by left-padding them with spaces)。空格可能无法直观地展示。我们可以使用ZEROFILL关键字设置表字段属性(注:这个属性会使字段自动使用unsigned)。这样的话,当该字段的值的长度小于定义的长度时,会在该值的前面补上相应的0。我们修改表的定义,重新插入数据进行验证。
mysql> CREATE TABLE `a_test` (
-> `id` bigint NOT NULL AUTO_INCREMENT,
-> `age` int(5) ZEROFILL DEFAULT NULL,
-> `name` varchar(5) DEFAULT NULL,
-> PRIMARY KEY (`id`)
-> ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Query OK, 0 rows affected (0.05 sec)
mysql> insert into a_test(id,age) values(1,1234);
Query OK, 1 row affected (0.00 sec)
mysql> select * from a_test;
+----+-------+------+
| id | age | name |
+----+-------+------+
| 1 | 01234 | NULL |
+----+-------+------+
1 row in set (0.01 sec)
1234只有4位,可以看到最后查询出来的结果中,最高位补了一个0。
总结
int(n)中的n并不会限制实际int的存储大小,依旧可以存4个字节的数据。n仅仅约束了在数值的宽度小于n时,返回的结果中值的高位会由空格填充。如果字段指定了ZEROFILL关键字,它的高位会由0
填充。
参考:
https://dev.mysql.com/doc/refman/8.0/en/numeric-type-attributes.html
https://juejin.cn/post/6873611171404972040

点个“赞 or 在看” 你最好看!

👇👇👇谢谢各位老板啦!!!




