如何在MySQL中设置默认字段值?

要设置默认字段值,请使用“默认”。让我们首先创建一个表-

create table DemoTable
-> (
-> Age int
-> );

这是在MySQL中设置默认字段值的查询-

alter table DemoTable MODIFY Age int default 18;
Records: 0 Duplicates: 0 Warnings: 0

现在您可以检查表说明-

desc DemoTable;

输出结果

这将产生以下输出-

+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| Age   | int(11) | YES  |     | 18      |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

使用insert命令在表中插入一些记录。我们留下了两个没有任何值的字段。因此,它将被设置为默认字段值-

insert into DemoTable values(19);

insert into DemoTable values();

insert into DemoTable values(20);

insert into DemoTable values();

使用select语句显示表中的所有记录-

mysql>select *from DemoTable;

输出结果

这将产生以下输出。如您所见,其中两个值都设置为18,因为我们在上面将其设置为默认值-

+------+
| Age  |
+------+
| 19   |
| 18   |
| 20   |
| 18   |
+------+
4 rows in set (0.00 sec)