如何在MySQL中为列设置默认值?
要设置默认值,请使用DEFAULT关键字。
让我们首先创建一个表-
create table DemoTable758 ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(100) );
以下是为列设置默认值的查询-
alter table DemoTable758 add column Colors ENUM('RED','GREEN','BLUE','ORANGE','YELLOW') DEFAULT 'YELLOW'; Records: 0 Duplicates: 0 Warnings: 0
让我们再次检查表的描述-
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命令在表中插入一些记录。在这里,我们没有使用名字“John”插入第二列的值。默认值“YELLOW”将放置在此处-
insert into DemoTable758(FirstName) values('John'); insert into DemoTable758(FirstName,Colors) values('Carol','RED');
使用select语句显示表中的所有记录-
select *from DemoTable758;
这将产生以下输出-
+----+-----------+--------+ | Id | FirstName | Colors | +----+-----------+--------+ | 1 | John | YELLOW | | 2 | Carol | RED | +----+-----------+--------+ 2 rows in set (0.00 sec)