mysql中tinyint(1)和tinyint(4)到底有什么区别

tinyint基础

tinyint存储使用了1个字节,就是8位,只能存储2^8即256个数字.在mysql实现中,有符号是-128-127,无符号是0-255,tinyint后面的括号带的数字,以后暂称之为M,那么1和4到底有什么区别呢?
接下来我们就探讨一下M的作用

先下结论

  1. 存储上没有任何区别,都是1个字节,8位
  2. 唯一的区别就是字段如何设置了zerofill零填充的时候,控制台返回的时候,会根据数字的长度自动填充成对应的位数,现在基本都是可视化操作了,这个特性,控制台,console才会用,几乎没啥作用

测试

实践出真知

1. 常规测试

使用基本的表,插入基本的数据

查询后发现没有任何区别

可以发现没有任何区别,实际上就是没有任何区别,如果你用navicat之类的工具试验,也会发现没有任何差别,详情可以参见引用stackoverflow用户AamirR的回答里面Aamir的回答可以做很好的验证

2. 无符号建表,同时zerofill

建表的基本语句是

最后查询结果如下,比较明显

zerofill的整数字段必须无符号,这里可以看出M显示出了特定的宽度,不够的时候会填充0,多余了不作处理

官方解释

这里查阅的官方文档是5.7英文版传送门

这里摘抄其中重要的一段

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 or not is up to the application.)

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. For example, a column specified as SMALLINT(3) has the usual SMALLINT range of -32768 to 32767, and values outside the range permitted by three digits are displayed in full using more than three digits.

When used in conjunction with the optional (nonstandard) attribute ZEROFILL, the default padding of spaces is replaced with zeros. For example, for a column declared as INT(4) ZEROFILL, a value of 5 is retrieved as 0005.

至此,也验证了我们的结论.

  1. M绝对和存储的值没有关系
  2. 无符号和zerofill的时候会填充0,显示成M对应的宽度
  3. 整数类型都一样,有默认的显示宽度
  4. M作为元数据存储,推荐是显示的宽度,但是最终的解释权归使用的程序所有

结论

最后,我的建议是,就是M其实没用,tinyint默认是4,其余的数字类型也有默认值,以后程序开发中,涉及整形数字的M时,可以不必纠结,直接忽略,使用数据库默认的M值即可