概述
MySQL有很多种数据类型,最常用的就是int,char,varchar,这些类型在创建表的时候都可以指定该字段的宽度,方法是在类型后面加一个括号,括号中写宽度就可以了。
但是,在指定宽度之后,有时候,我们可以看到插入的数据有一些被截断了;有一些并没有截断,而是四舍五入了,甚至什么操作都没有,原样插入了。
下面对于每一种数据类型单独测试:
数字型(int、tinyint...)
mysql> create table t (id int(5));
mysql> insert into t values(1234567),(123),(12345);
mysql> select * from t;
+---------+
| id |
+---------+
| 1234567 |
| 123 |
| 12345 |
+---------+
从上面的例子中可以看到,对于int而言,虽然指定了宽度,但是当插入的数据宽度大于指定的宽度时,并不会截断。
其实对于int而言,要指定宽度,那么就必定要指定zerofill,但同样,zerofill只是在宽度不够的时候用0填充,但是宽度大于指定宽度时,数据仍然不会被截取。
mysql> create table t (id int(5) zerofill);
mysql> insert into t values(1234567),(123),(12345);
mysql> select * from t;
+---------+
| id |
+---------+
| 1234567 |
| 00123 |
| 12345 |
+---------+
字符串型(char、varchar)
mysql> create table t (fields_1 char(5),fields_2 varchar(5));
Query OK, 0 rows affected (0.01 sec)
mysql> insert into t values("123","123"),("12345","12345"),("1234567","1234567");
Query OK, 3 rows affected, 2 warnings (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 2
mysql> show Warnings;
+---------+------+-----------------------------------------------+
| Level | Code | Message |
+---------+------+-----------------------------------------------+
| Warning | 1265 | Data truncated for column 'fields_1' at row 3 |
| Warning | 1265 | Data truncated for column 'fields_2' at row 3 |
+---------+------+-----------------------------------------------+
2 rows in set (0.00 sec)
mysql> select fields_1,length(fields_1),fields_2,length(fields_2) from t;
+----------&