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

1. tinyint存储只是用一个字节,就是8位,只能存储2^8个数字,也就是256个数字,在mysql实现中,有符号是-128-127,无符号是0-255

2. tinyint后面的括号带的数字,以后称之为M,和存贮的值没有任何关系,只是在某些情况下和显示的宽度有关系
特殊的在java中,数据库中的tinyint(1)会自动转换为java中的boolean类型,tinyint(4)正常转换为数字int类型

1. 常规测试

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

基本表

查询后发现没有任何区别 

基本测试

可以发现没有任何区别,实际上就是没有任何区别,如果你用navicat之类的工具试验,也会发现没有任何差别,详情可以参见引用> sqldatatypes - MySql: Tinyint (2) vs tinyint(1) - what is the difference? - Stack Overflow 里面Aamir的回答可以做很好的验证

2. 无符号建表,同时zerofill

建表的基本语句是 

无符号建表

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

无符号查询

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

官方文档的解释是,5.7英文版

MySQL :: MySQL 5.7 Reference Manual :: 11.1.6 Numeric Type Attributes

这里摘抄其中重要的一段

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. 绝对和存储的值没有关系
  2. mysql的console中也会忽略这些
  3. 无符号和zerofill的时候会填充0,显示成M对应的宽度
  4. 整数类型都一样,有默认的显示宽度
  5. M作为元数据存储,推荐是显示的宽度,但是最终的解释权归程序所有

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

转载于:https://my.oschina.net/DavidRicardo/blog/869169

相关资源:数据库MySQL-union(联合)_union-其它代码类资源-CSDN文库

猜你喜欢

转载自blog.csdn.net/HD243608836/article/details/120974847