如何在 MySQL 中设置默认字段值?
mysqlmysqli database更新于 2025/5/21 8:44:17
要设置默认字段值,请使用"default"。让我们首先创建一个表 −
mysql> create table DemoTable -> ( -> Age int -> ); Query OK, 0 rows affected (0.58 sec)
以下是在 MySQL 中设置默认字段值的查询 −
mysql> alter table DemoTable MODIFY Age int default 18; Query OK, 0 rows affected (0.25 sec) Records: 0 Duplicates: 0 Warnings: 0
现在您可以检查表描述 −
mysql> desc DemoTable;
输出
这将产生以下输出 −
+-------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+-------+ | Age | int(11) | YES | | 18 | | +-------+---------+------+-----+---------+-------+ 1 row in set (0.00 sec)
使用 insert 命令在表中插入一些记录。我们留下了两个字段没有任何值。因此,它将被设置为默认字段值 −
mysql> insert into DemoTable values(19); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(); Query OK, 1 row affected (0.11 sec)
使用 select 语句显示表中的所有记录 −
mysql>select *from DemoTable;
输出
这将产生以下输出。如您所见,其中两个值设置为 18,因为我们已经设置了与上面的默认值相同的值 −
+------+ | Age | +------+ | 19 | | 18 | | 20 | | 18 | +------+ 4 rows in set (0.00 sec)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

