12、MySQL-默认值约束(DEFAULT)

时间:2022-11-16 10:03:57
一般默认值约束会和非空约束同时使用格式 CREATE TABLE tbl_name(    字段名称 字段类型 DEFAULT 默认值 );

mysql> CREATE TABLE IF NOT EXISTS testDF(
    -> id INT,
    -> username VARCHAR(20) NOT NULL DEFAULT 'HAHA'
    -> );
Query OK, 0 rows affected (0.08 sec)

mysql> DESC testDF;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id       | int(11)     | YES  |     | NULL    |       |
| username | varchar(20) | NO   |     | HAHA    |       |
+----------+-------------+------+-----+---------+-------+
2 rows in set (0.08 sec)

mysql> INSERT testDF(id,username) VALUES(11,'AAA');
mysql> INSERT testDF(username) VALUES('BBB');
mysql> INSERT testDF(id) VALUES(333);

mysql> SELECT * FROM testDF;
+------+----------+
| id   | username |
+------+----------+
|   11 | AAA      |
| NULL | BBB      |
|  333 | HAHA     |
|  444 | HAHA     |
+------+----------+