关于int(M)后面参数的一点research

来源:互联网 发布:ce6.7源码 编辑:程序博客网 时间:2024/06/18 15:31

又遇到int后面参数这个问题,整理下。

mysql中,int存储需要占用4个字节,无论存的是324123,还是1,与存储数字大小无关。

有符号时,最小值为-2147483648(注意这里是11位显示宽度),最大值为2147483648(此处为10位显示宽度)

无符号时(unsigned),最小值为0,最大值为4294967295(注意这里是10位显示宽度)。

在mysql创建表中,大家可以发现,假如不指定int的长度时,默认是11。为什么是11呢,不是12,不是10?

这是因为默认mysql会设置为每种类型的‘最长'值长度,比如上面可以看到,有符号类型的int最大显示宽度是11位(有个负号),所以是11.

假如你勾选了unsigned,即无符号类型,则为10.

再看看M的意思,官方文档说明是‘display width'显示宽度。原文‘MySQL supports an extension for optionally specifying the display width of integer data types in parentheses following the base keyword for the type.

从字面上看,好像是我存个int(4),它就只能显示4位数字。其实不然,文档上说‘The display width does not constrain the range of values that can be stored in the column. Nor does it prevent values wider than the column display width from being displayed correctly.’,它不是为了限制字段值的存储范围,也不是为了限制那些超过该列指定宽度值的可显示位数。也就是说,设定了int(4),还是能够存储12345的数字,也能存储数字1.

它是为了在值不足M位时左边补足用的,有另外一个参数叫zerofill,默认不指定,则不足M位数时,左补空格;指定了,则补0.

比如设置了int(4) zerofill,存储12,mysql会在左边补足0,成为‘0012’;没有设置zerofill,则为‘  12’。这里要注意的是,在mysql的cli命令行中,是不用显示宽度的,除非是设置了zerofill,所以一般我们看不到那些补足的空格,但是其他的客户端程序可以。这里面php连接获取值为什么不是‘  12’,我也不知道,还需要再研究,可能是php做了trim。可以参看https://blogs.oracle.com/jsmyth/entry/what_does_the_11_mean 

还可以发现,mysql最大可以设置的M为255,不知道为什么。。

还有待更新

参看官方文档:http://dev.mysql.com/doc/refman/5.6/en/numeric-type-attributes.html

和 http://stackoverflow.com/questions/7552223/int11-vs-intanything-else

0 0
原创粉丝点击