如何设置 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)
广告