问题:int(255) 数据类型的容量,比int(1)更多吗?
遇到问题,第一反应是去查说明书,可以在mysql document 中找到int这种数据类型的容量是多少,Integer Types (Exact Value)
里面只提到了 INT的容量,"signed有符号数字"是2147683647,也就是说只要“一个被插入的数字”在[-2147483648,+2147483647]这个范围里,都是可以用 INT 这个容器来装的,为什么负数范围比正数范围要多1呢?因为还有一个0占了一位,还要注意的是,每个MYSQL version的INT容量是不同的
document 没有提及到INT(size)这个东西,这说明不管是INT(1)还是INT(10),容量都是一样的,都是[-2147483648,+2147483647],我们可以验证一下,我们插入INT能承受的“最大正值”和“最小负值”
create table table1(
column1 int,
column2 int(1),
column3 int(10),
column4 int(255)
);
insert into table1 values (2147483647,2147483647,2147483647,2147483647);
insert into table1 values (-2147483648,-2147483648,-2147483648,-2147483648);
mysql> select * from table1;
+-------------+-------------+-------------+-------------+
| column1 | column2 | column3 | column4 |
+-------------+-------------+-------------+-------------+
| 2147483647 | 2147483647 | 2147483647 | 2147483647 |
| -2147483648 | -2147483648 | -2147483648 | -2147483648 |
+-------------+-------------+-------------+-------------+
2 rows in set (0.00 sec)
结果是完全一样的,那int(1)和int(10)的区别在哪里呢?
其实INT(size) 中的size是指”显示的最大值“,如果你定义了INT(5)
1.”插入数字的位数“小于5位,那么剩下的位数就会用0在左边补齐(在字段fillzero属性下才显示区别)
2.”插入数字的位数“大于5位,那就正常显示(不可能砍掉你的位数)
delimiter EOF
drop table if exists table1;
create table table1(
column1 int(5) zerofill
);
insert into table1 values (1);
insert into table1 values (21);
insert into table1 values (321);
insert into table1 values (654321);
select * from table1;
EOF
delimiter ;
得到的结果是
+---------+
| column1 |
+---------+
| 00001 |
| 00021 |
| 00321 |
| 654321 |
+---------+
所以int(size)中的size是为了对齐使用的,在MySQL用添加0的方式对齐,看起来更不美观,这时因为”这种对齐“不是给MySQL看的,而是给连接MySQL的应用程序看的,应用程序用的是”空格“来补齐,而不是用”0“,当然逻辑层也可以使用代码去实现这一点,只是MySQL有这个功能而已
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 or not is up to the application.)
详细阅读