如何將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)
使用`insert`命令在表中插入一些記錄。查詢如下:
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
現在您可以檢查表記錄,其中`Id`為6的`Age`列為NULL。查詢如下:
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()`函式。在這裡,將`Id`為6的`Salary`列更新為預設值。查詢如下:
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已成功更新。
廣告