欢迎各位兄弟 发布技术文章
这里的技术是共享的
not null 是你对插入数据的约束
default 是你在在插入数据时,如果这个字段值缺省的时候所插入的值,
如果你插入有值那么就用不到default
mysql> desc test; #default为null
+--------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------------------+------+-----+---------+----------------+
| cid | tinyint(3) unsigned | NO | PRI | NULL | auto_increment |
| course | varchar(50) | NO | UNI | NULL | |
+--------+---------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
mysql> insert into test (cid) values(1); # 如果不给默认值,它就会报错
ERROR 1364 (HY000): Field 'course' doesn't have a default value
如果 修改了表后 , course 列可以有默认值
mysql> alter table test modify course varchar(50) null ;
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc test; #此时 course 可以有默认值
+--------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------------------+------+-----+---------+----------------+
| cid | tinyint(3) unsigned | NO | PRI | NULL | auto_increment |
| course | varchar(50) | YES | UNI | NULL | |
+--------+---------------------+------+-----+---------+----------------+
mysql> insert into test (cid) values(1); # 此时可以插入成功
Query OK, 1 row affected (0.00 sec)
mysql> select * from test;
+-----+--------+
| cid | course |
+-----+--------+
| 1 | NULL |
+-----+--------+
1 row in set (0.00 sec)
mysql>
来自 https://zhidao.baidu.com/question/810834579532050612.html