首页 > 代码库 > 默认约束(DEFAULT)

默认约束(DEFAULT)

默认值

当插入记录时,如果没有明确为字段赋值,则自动赋予默认值。

mysql> CREATE TABLE tb8(
-> id SMALLINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
-> usename VARCHAR(20) NOT NULL UNIQUE KEY,
-> sex ENUM(‘1‘,‘2‘,‘3‘) DEFAULT ‘3‘
-> );
Query OK, 0 rows affected (0.11 sec)

mysql> SHOW COLUMNS FROM tb8;
+---------+----------------------+------+-----+---------+----------------+
| Field       | Type                        | Null   | Key  | Default   | Extra              |
+---------+----------------------+------+-----+---------+----------------+
| id           | smallint(5) unsigned  | NO    | PRI   | NULL     | auto_increment|
| usename | varchar(20)              | NO    | UNI   | NULL     |                       |
| sex         | enum(‘1‘,‘2‘,‘3‘)        | YES  |         | 3           |                        |
+---------+----------------------+------+-----+---------+----------------+
3 rows in set (0.03 sec)

mysql> INSERT tb8(usename) VALUES(‘Tom‘); #插入记录
Query OK, 1 row affected (0.03 sec)

mysql> SELECT * FROM tb8;  #查看记录
+----+---------+------+
| id    | usename| sex   |
+----+---------+------+
| 1     | Tom      | 3       |
+----+---------+------+
1 row in set (0.00 sec)

默认约束(DEFAULT)