将 MySQL 字段重置为默认值?

王林
王林 转载
2023-08-27 15:29:02 1026浏览

将 MySQL 字段重置为默认值?

在 MySQL 中,有两种方法可以将 MySQL 字段重置为默认值。一种是default关键字,另一种是default()函数。

情况1:使用default关键字。语法如下:

UPDATE yourTableName SET yourColumnName=default where yourCondition;

情况 2:使用 default() 函数。语法如下:

UPDATE yourTableName SET yourColumnName=default(yourColumnName) where yourCondition;

为了理解上述语法,让我们创建一个表。创建表的查询如下:

mysql> create table Default_Demo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(20),
   -> Age int,
   -> Salary float,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.73 sec)

使用插入命令在表中插入一些记录。查询如下:

mysql> insert into Default_Demo(Name,Age,Salary) values('John',23,405.56);
Query OK, 1 row affected (0.18 sec)
mysql> insert into Default_Demo(Name,Age,Salary) values('Carol',25,1000.98);
Query OK, 1 row affected (0.22 sec)
mysql> insert into Default_Demo(Name,Age,Salary) values('Larry',21,987.24);
Query OK, 1 row affected (0.09 sec)
mysql> insert into Default_Demo(Name,Age,Salary) values('Sam',24,986.10);
Query OK, 1 row affected (0.17 sec)
mysql> insert into Default_Demo(Name,Age,Salary) values('Mike',22,10000.50);
Query OK, 1 row affected (0.17 sec)
mysql> insert into Default_Demo(Name,Age,Salary) values('David',26,100.45);
Query OK, 1 row affected (0.20 sec)

使用 select 语句显示表中的所有记录。查询如下:

mysql> select *from Default_Demo;

以下是输出:

+----+-------+------+---------+
| Id | Name  | Age  | Salary  |
+----+-------+------+---------+
|  1 | John  |   23 | 405.56  |
|  2 | Carol |   25 | 1000.98 |
|  3 | Larry |   21 | 987.24  |
|  4 | Sam   |   24 | 986.1   |
|  5 | Mike  |   22 | 10000.5 |
|  6 | David |   26 | 100.45  |
+----+-------+------+---------+
6 rows in set (0.00 sec)

这是将 MySQL 字段重置为默认值的查询。

情况 1: 使用 default 关键字。查询如下:

mysql> update Default_Demo set Age=Default where Id=6;
Query OK, 1 row affected (0.10 sec)
Rows matched: 1 Changed: 1 Warnings: 0

现在可以查看表记录,Age列为NULL,Id为6,查询如下:

mysql> select *from Default_Demo;

以下是输出:

+----+-------+------+---------+
| Id | Name  | Age  | Salary  |
+----+-------+------+---------+
|  1 | John  |   23 | 405.56  |
|  2 | Carol |   25 | 1000.98 |
|  3 | Larry |   21 | 987.24  |
|  4 | Sam   |   24 | 986.1   |
|  5 | Mike  |   22 | 10000.5 |
|  6 | David | NULL | 100.45  |
+----+-------+------+---------+
6 rows in set (0.00 sec)

查看 ID 6,其中 Age 列已更新为默认值 NULL。

情况 2: 现在您还可以使用 default() 函数。这里,将 Salary 列更新为默认值,其中 Id 为 6。查询如下:

mysql> update Default_Demo set Salary=Default(Salary) where Id=6;
Query OK, 1 row affected (0.21 sec)
Rows matched: 1 Changed: 1 Warnings: 0

现在检查Id为6的表记录。

mysql> select *from Default_Demo where Id=6;

以下是输出:

+----+-------+------+--------+
| Id | Name  | Age  | Salary |
+----+-------+------+--------+
|  6 | David | NULL | NULL   |
+----+-------+------+--------+
1 row in set (0.00 sec)

查看salary列默认值NULL更新成功。

以上就是将 MySQL 字段重置为默认值?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除