mysql int多长 int(1)类型的值范围是多少呢

MySQL支持多种数据类型,大致可以分为三类:数值、日期/时间和字符串(字符)类型。其中, 整数类型包括:tinyint、smallint、mediumint、int和bigint。 默认都是有符号的。

变为无符号,需要手动加unsigned。

age int unsigned

age tinyint unsigned

int(n)中不论n指定为多少,范围都一样-2~31~2^31-1,都能插入9位数字。n只是用来控制显示而已,如果为int(4),插入一个1,显示时也会用空格补齐到4个字节

请问所有mysql中的数据类型中的(n)都是表示显示位数吗?

并非如此,NUMERIC(4)就限定了取值范围,超过4位就不允许写入了。因此如果你想限定数字的取值范围,最好是用NUMERIC来定义。

在MySQL的数据类型中,Tinyint的取值范围是:带符号的范围是-128到127。无符号的范围是0到255

Tinyint占用1字节的存储空间,即8位(bit)。

    其中,tinyint的大小为1字节,即8位二进制。在无符号的情况下,值得范围(0,255)。在有符号的情况下,值得范围(-128,127)。本文将通过测试验证tinyint值的范围。

1.有符号
1.1建表
    创建表person,包含name 和score两列。其中score的类型是Tinyint,默认为有符号。

扫描二维码关注公众号,回复: 13559838 查看本文章

create table person (
  name varchar(20),
  score tinyint
);
1.2插入数据
mysql> insert into person values('April',128);
ERROR 1264 (22003): Out of range value for column 'score' at row 1
mysql> insert into person values('April',127);
Query OK, 1 row affected (0.00 sec)

 插入128时报错,原因是值越界。插入127时成功。这验证了tinyint在有符号的情况下,上界是127。

mysql> insert into person values('April',-129);
ERROR 1264 (22003): Out of range value for column 'score' at row 1
mysql> insert into person values('April',-128);
Query OK, 1 row affected (0.00 sec)

插入-129时报错,原因是值越界。插入-128时成功。这验证了tinyint在有符号的情况下,下界是-128。

1.3 查询数据
select * from person;

2.无符号 
2.1建表

创建表person,包含name 和score两列。其中score的类型是Tinyint unsigned 。

create table person (
  name varchar(20),
  score tinyint unsigned
);
2.2插入数据
mysql> insert into person values('April',256);
ERROR 1264 (22003): Out of range value for column 'score' at row 1
mysql> insert into person values('April',255);
Query OK, 1 row affected (0.00 sec)
    插入256时报错,原因是值越界。插入255时成功。这验证了tinyint在无符号的情况下,上界是255。

mysql> insert into person values('April',-1);
ERROR 1264 (22003): Out of range value for column 'score' at row 1
mysql> insert into person values('April',0);
Query OK, 1 row affected (0.00 sec)
    插入-1时报错,原因是值越界。插入0时成功。这验证了tinyint在无符号的情况下,下界是0。

2.3查询数据
select * from person;
   

    综上,tinyint在无符号的情况下,值得范围(0,255)。在有符号的情况下,值得范围(-128,127)。

猜你喜欢

转载自blog.csdn.net/sunyufeng22/article/details/121145684