MySQL中的unsigned和zerofill

unsigned

其意思为无符号的意思,在创建表中,字段添加此项可以令字段只能保存正数,并且可以增大数据类型的可用范围。

创建一个表,用于测试

mysql> create table test(num1 int,num2 int unsigned);

在其中一个字段中添加unsigned,往里面插入数据时,就会发现区别了。

往两个字段中添加负数,测试结果

mysql> insert into test values(-222,-233);
ERROR 1264 (22003): Out of range value for column 'num2' at row 1

显示num2字段插入的数据超出范围,-233在int的范围之内,但因为添加了unsigned字段,使num2字段不能为负数。

换成整数,插入查看

mysql> insert into test values(-222,233);
Query OK, 1 row affected (0.00 sec)

mysql> select * from test;
+------+------+
| num1 | num2 |
+------+------+
| -222 |  233 |
+------+------+

这样数据就出入成功了,查看一下结构

mysql> desc test;
+-------+------------------+------+-----+---------+-------+
| Field | Type             | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| num1  | int(11)          | YES  |     | NULL    |       |
| num2  | int(10) unsigned | YES  |     | NULL    |       |
+-------+------------------+------+-----+---------+-------+

unsigned常用于一些数据不能为负数的场合。

zerofill

zerofill的作用是填充0,在字段中数据类型规定的范围中,若是插入的数据不满足范围,则会使用空格作为填充,使其符合要求,而zerofill则会将空格改为0。

创建一个表,用于测试

mysql> create table test2(num1 int(5),num2 int(5) zerofill);

规定num1和num2的数值宽度为5,若是插入的数值不足5位,则num1使用空格填充,num2使用0填充。

插入数据并查看

mysql> insert into test2 values(1,1);
Query OK, 1 row affected (0.01 sec)

mysql> select * from test2;
+------+-------+
| num1 | num2  |
+------+-------+
|    1 | 00001 |
+------+-------+

查看结构

mysql> desc test2;
+-------+--------------------------+------+-----+---------+-------+
| Field | Type                     | Null | Key | Default | Extra |
+-------+--------------------------+------+-----+---------+-------+
| num1  | int(5)                   | YES  |     | NULL    |       |
| num2  | int(5) unsigned zerofill | YES  |     | NULL    |       |
+-------+--------------------------+------+-----+---------+-------+

定义填充符为0后,默认就会将unsigned项添加进去,因为以0开头的,不可能是负数。

对于数据类型后的()不清楚可以转到===>一键飞行<===查看。

发布了167 篇原创文章 · 获赞 27 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42534026/article/details/105716264