MySQL int(4)类型的值范围是多少呢?


mysql> create table t1 (a int(4));
Query OK, 0 rows affected (0.14 sec)

mysql> insert into t1 values(15652);
Query OK, 1 row affected (0.06 sec)

mysql> insert into t1 values(156522);
Query OK, 1 row affected (0.05 sec)

mysql> insert into t1 values(15652256145);
ERROR 1264 (22003): Out of range value adjusted for column 'a' at row 1
mysql> insert into t1 values(1565222);
Query OK, 1 row affected (0.06 sec)

mysql> insert into t1 values(15652222);
Query OK, 1 row affected (0.08 sec)

mysql> insert into t1 values(156522222);
Query OK, 1 row affected (0.05 sec)

mysql> insert into t1 values(1565222222);
Query OK, 1 row affected (0.03 sec)

mysql> insert into t1 values(1565222222)2;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near '2' at
line 1
mysql>

为什么int(4)类型的字段可以插入9位的数字呢?

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

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

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

你可能感兴趣的:(MySQL,数据库)