什么是tinyint(m)?先来了解下mysql中字符串类型varchar(m) 和数值类型tinyint(m) 的区别?
字符串列类型: varchar(m) 而言,m 是字段中可以存储的最大字符长度,也就是说是字段长度。根据设置,当你插入超出字段长度的数据时,你很可能会收到错误提示,即使没有收到错误提示,你插入的数据也会被自动截断以适应该字段的预定义长度。所以,varchar(20) 和 varchar(40) 是不同的,其真实反映了该字段可以存储的数据长度。
数值列类型:其长度修饰符表示最大显示宽度,与该字段物理存储没有任何关系。也就是说,tinyint(1) 和 tinyint(4) 能够存储的数值范围都是-128…127 (or for unsigned values 0…255),他们是相同的数据类型,当然他们还是有一点差异,以下会有说明。
对于 tinyint 数据类型,只占 1 个字节:
- 无符号的(unsigned),范围是 0 到 255,默认长度是 3。
- 有符号的(signed),范围是 -128 到 127,默认长度是 4。
范围算法:tinyint占1个字节,一个字节 8 位,也就是1*8=8,可以表示的数字个数是 2的 8 次方(2^8 = 256个数字)。
区别:若使用了 zerofill,当实际长度达不到指定的显示长度时,就会用 0 在前面补齐。(简记zerofill作用就是补零)
测试先创建一张测试表,对 tinyint 类型都使用 zerofill。
create table `pre_demo` ( `id` int(10) unsigned not null auto_increment comment '主键', `unsigned_t` tinyint(3) unsigned zerofill not null default '000', `signed_t` tinyint(4) unsigned zerofill not null default '0000', `t1` tinyint(1) unsigned zerofill not null default '0', `t2` tinyint(2) unsigned zerofill not null default '00', `t3` tinyint(3) unsigned zerofill not null default '000', `t4` tinyint(4) unsigned zerofill not null default '0000', `t5` tinyint(5) unsigned zerofill not null default '00000', primary key (`id`)) engine=innodb default charset=utf8 collate=utf8_unicode_ci;
然后,插入测试数据。
nsert into pre_demo values(null,8,8,8,8,8,8,8);insert into pre_demo values(null,123,123,123,123,123,123,123);
最后,查询数据表中的数据。
mysql> select * from pre_demo;+----+------------+----------+-----+-----+-----+------+-------+| id | unsigned_t | signed_t | t1 | t2 | t3 | t4 | t5 |+----+------------+----------+-----+-----+-----+------+-------+| 1 | 008 | 0008 | 8 | 08 | 008 | 0008 | 00008 || 2 | 123 | 0123 | 123 | 123 | 123 | 0123 | 00123 |+----+------------+----------+-----+-----+-----+------+-------+2 rows in set (0.00 sec)
mysql> select *,length(id),length(unsigned_t),length(t1) from pre_demo;+----+------------+----------+-----+-----+-----+------+-------+------------+--------------------+------------+| id | unsigned_t | signed_t | t1 | t2 | t3 | t4 | t5 | length(id) | length(unsigned_t) | length(t1) |+----+------------+----------+-----+-----+-----+------+-------+------------+--------------------+------------+| 1 | 008 | 0008 | 8 | 08 | 008 | 0008 | 00008 | 1 | 3 | 1 || 2 | 123 | 0123 | 123 | 123 | 123 | 0123 | 00123 | 1 | 3 | 3 |+----+------------+----------+-----+-----+-----+------+-------+------------+--------------------+------------+2 rows in set (0.00 sec)
以上就是mysql tinyint(1)与tinyint(4)的区别是什么的详细内容。