MySQL数据类型 int(M) 表示什么意思?

来源:互联网 发布:refa有用吗 知乎 编辑:程序博客网 时间:2024/04/29 08:40

MySQL 数据类型中的 integer types 有点奇怪。你可能会见到诸如:int(3)、int(4)、int(8) 之类的 int 数据类型。刚接触 MySQL 的时候,我还以为 int(3) 占用的存储空间比 int(4) 要小, int(4) 占用的存储空间比 int(8) 小。

 

后来,参看 MySQL 手册,发现自己理解错了。int(M): M indicates the maximum display width for integer types.

 

在 integer 数据类型中,M 表示最大显示宽度。原来,在 int(M) 中,M 的值跟 int(M) 所占多少存储空间并无任何关系。 int(3)、int(4)、int(8) 在磁盘上都是占用 4 btyes 的存储空间。说白了,除了显示给用户的方式有点不同外,int(M) 跟 int 数据类型是相同的。

 

另外,int(M) 只有跟 zerofill 结合起来,才能使我们清楚的看到不同之处。

 

mysql> drop table if exists t;mysql> create table t(id int zerofill);

 

mysql> insert into t(id) values(10);

 

mysql> select * from t;

 

+------------+

| id             |

+------------+

| 0000000010 |

+------------+

 

mysql> alter table t change column id id int(3) zerofill;

 

mysql> select * from t;

 

+------+

| id |

+------+

| 010 |

+------+

 

 

mysql>mysql> alter table t change column id id int(4) zerofill;

mysql> select * from t;

+------+

| id |

+------+

| 0010 |

+------+

 

 

mysql>mysql> insert into t(id) values(1000000);

mysql> select * from t;

+---------+

| id |

+---------+

| 0010 |

| 1000000 |

+---------+

 

从上面的测试可以看出,“(M)”指定了 int 型数值显示的宽度,如果字段数据类型是 int(4),则:当显示数值 10 时,在左边要补上 “00”;当显示数值 100 是,在左边要补上“0”;当显示数值 1000000 时,已经超过了指定宽度“(4)”,因此按原样输出。在使用 MySQL 数据类型中的整数类型(tinyint, smallint, mediumint, int/integer, bigint)时,非特殊需求下,在数据类型后加个“(M)”,我想不出有何意义。

 

另外,在 MySQL 数据类型中,integer 和 int 同义。到底使用哪个,自己看着办吧。

原创粉丝点击