mysql中列的默认值

在 MySQL 中,每个字段定义都包含附加约束或者修饰符,这些可以用来增加对所输入数据的约束。

NULL 和 NOT NULL 修饰符、DEFAULT 修饰符,AUTO_INCREMENT 修饰符。

NULL 和 NOT NULL 修饰符

可以在每个字段后面都加上这 NULL 或 NOT NULL 修饰符来指定该字段是否可以为空(NULL),

还是说必须填上数据 (NOT NULL)。MySQL 默认情况下指定字段为 NULL 修饰符,如果一个字段指定为NOT NULL,

MySQL 则不允许向该字段插入空值(这里面说的空值都为 NULL),因为这是 “规定”。

但是在自增列和 TIMESTAMP 字段中,这个规则并不适用。

向这些字段中插入 NULL 值将会导致插入下一个自动增加的值或者当前的时间戳。

mysql> create table t10 (
    -> id int not null default 0,
    -> name char(10) not null default ''
    -> );
Query OK, 0 rows affected (0.01 sec)
#插入2个值是ok的.
mysql> insert into t10 values (1,"lisi");
Query OK, 1 row affected (0.08 sec)
#只插入一个值,也是ok的.
mysql> insert into t10 (id) values (2);
Query OK, 1 row affected (0.00 sec)
#发现未插入的name列继承default的“”值.
mysql> select * from t10;
+----+------+
| id | name |
+----+------+
|  1 | lisi |
|  2 |      |
+----+------+
2 rows in set (0.00 sec)
mysql> select * from t10 where name = '';
+----+------+
| id | name |
+----+------+
|  2 |      |
+----+------+
1 row in set (0.00 sec)

#创建t11表,字段id,name不为null.
mysql> create table t11 ( id int not null, name char(10) not null);
Query OK, 0 rows affected (0.01 sec)
#如果只插入其中一列,发现报错,其中另一列不能为空.
mysql> insert into t11 (id) values (2);
ERROR 1364 (HY000): Field 'name' doesn't have a default value
#如果第二列插入"null"也会报错,设置字段为not null.
mysql> insert into t11 (id,name) values (2,null);
ERROR 1048 (23000): Column 'name' cannot be null
#插入“0”,""字段是ok的.
mysql> insert into t11 (id,name) values (2,0);
Query OK, 1 row affected (0.00 sec)
mysql> insert into t11 (id,name) values (2,"");
Query OK, 1 row affected (0.01 sec)


结论:

如果一个字段中没有指定 DEFAULT 修饰符,MySQL 会依据这个字段是 NULL 还是 NOT NULL 自动设置默认值。

如果指定字段可以为 NULL,则 MySQL 为其设置默认值为 NULL。

如果是 NOT NULL 字段,MySQL 对于数值类型插入 0,字符串类型插入空字符串.


猜你喜欢

转载自blog.51cto.com/215687833/2349837