在 MySQL 中,如何替換特定表的特定欄位中的所有 NULL 值?


要替換特定表中特定欄位中的所有空值,請使用 UPDATE 命令和 IS NULL 屬性。語法如下:

UPDATE yourTableName SET yourColumnName=”yourValue’ WHERE yourColumnName IS NULL;

為了理解以上語法,我們建立一個表。建立表的查詢如下:

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

使用 insert 命令在表中插入一些記錄。用於插入記錄的查詢如下:

mysql> insert into Employee_Information_Table(Name,Salary) values('John',NULL);
Query OK, 1 row affected (0.13 sec)

mysql> insert into Employee_Information_Table(Name,Salary) values('Carol',NULL);
Query OK, 1 row affected (0.17 sec)

mysql> insert into Employee_Information_Table(Name,Salary) values('Bob',NULL);
Query OK, 1 row affected (0.10 sec)

mysql> insert into Employee_Information_Table(Name,Salary) values('David',NULL);
Query OK, 1 row affected (0.17 sec)

mysql> insert into Employee_Information_Table(Name,Salary) values('Robert',NULL);
Query OK, 1 row affected (0.12 sec)

mysql> insert into Employee_Information_Table(Name,Salary) values('Mike',NULL);
Query OK, 1 row affected (0.24 sec)

mysql> insert into Employee_Information_Table(Name,Salary) values('Sam',NULL);
Query OK, 1 row affected (0.17 sec)

使用 select 語句顯示錶中的所有記錄。查詢如下:

mysql> select *from Employee_Information_Table;

以下是輸出:

+----+--------+--------+
| Id | Name   | Salary |
+----+--------+--------+
|  1 | John   |   NULL |
|  2 | Carol  |   NULL |
|  3 | Bob    |   NULL |
|  4 | David  |   NULL |
|  5 | Robert |   NULL |
|  6 | Mike   |   NULL |
|  7 | Sam    |   NULL |
+----+--------+--------+
7 rows in set (0.00 sec)

以下是對特定表中特定欄位替換所有空值的查詢。查詢如下:

mysql> update Employee_Information_Table
   -> set Salary=45500 where Salary IS NULL;
Query OK, 7 rows affected (0.23 sec)
Rows matched: 7 Changed: 7 Warnings: 0

現在再次檢查表記錄。所有空值都已更新為某個值。以下是使用 select 語句從表中列出所有記錄的查詢:

mysql> select *from Employee_Information_Table;

以下是輸出:

+----+--------+--------+
| Id | Name   | Salary |
+----+--------+--------+
|  1 | John   |  45500 |
|  2 | Carol  |  45500 |
|  3 | Bob    |  45500 |
|  4 | David  |  45500 |
|  5 | Robert |  45500 |
|  6 | Mike   |  45500 |
|  7 | Sam    |  45500 |
+----+--------+--------+
7 rows in set (0.00 sec)

更新於: 30-7-2019

237 次瀏覽

開啟你的職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.