MySQL 如何设置列的默认值
要设置默认值,请使用DEFAULT关键字。
让我们首先创建一个表 –
mysql> create table DemoTable758 (
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
FirstName varchar(100)
);
Query OK, 0 rows affected (0.66 sec)
以下是为列设置默认值的查询 –
mysql> alter table DemoTable758 add column Colors ENUM('RED','GREEN','BLUE','ORANGE','YELLOW') DEFAULT 'YELLOW';
Query OK, 0 rows affected (0.44 sec)
Records: 0 Duplicates: 0 Warnings: 0
让我们再次检查表的描述 –
mysql> desc DemoTable758;
这将产生以下输出结果 –
+-----------+----------------------------------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+----------------------------------------------+------+-----+---------+----------------+
| Id | int(11) | NO | PRI | NULL | auto_increment |
| FirstName | varchar(100) | YES | | NULL | |
| Colors | enum('RED','GREEN','BLUE','ORANGE','YELLOW') | YES | | YELLOW | |
+-----------+----------------------------------------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
使用insert命令在该表中插入一些记录。在这里,我们没有为FirstName为“John”的第2列插入值。默认值“YELLOW”将被放置在那里 –
mysql> insert into DemoTable758(FirstName) values('John');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable758(FirstName,Colors) values('Carol','RED');
Query OK, 1 row affected (0.17 sec)
使用select语句从表中显示所有记录 –
mysql> select *from DemoTable758;
这将产生以下输出结果 –
+----+-----------+--------+
| Id | FirstName | Colors |
+----+-----------+--------+
| 1 | John | YELLOW |
| 2 | Carol | RED |
+----+-----------+--------+
2 rows in set (0.00 sec)
阅读更多:MySQL 教程