使用 IF 條件的 MySQL UPDATE


執行MySQL中的更新操作使用IF條件,如下所示 −

update yourTableName set yourColumnName =if(yourColumnName =yourOldValue,yourNewValue,yourColumnName);

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

mysql> create table updateIfConditionDemo
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserName varchar(20),
   -> UserAge int
   -> );
Query OK, 0 rows affected (4 min 0.59 sec)

現在,你可以使用 insert 命令插入一些記錄到表中。查詢如下 −

mysql> insert into updateIfConditionDemo(UserName,UserAge) values('Larry',23);
Query OK, 1 row affected (0.11 sec)
mysql> insert into updateIfConditionDemo(UserName,UserAge) values('Mike',21);
Query OK, 1 row affected (0.20 sec)
mysql> insert into updateIfConditionDemo(UserName,UserAge) values('Sam',23);
Query OK, 1 row affected (0.15 sec)
mysql> insert into updateIfConditionDemo(UserName,UserAge) values('David',23);
Query OK, 1 row affected (0.14 sec)
mysql> insert into updateIfConditionDemo(UserName,UserAge) values('Maxwell',23);
Query OK, 1 row affected (0.18 sec)

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

mysql> select *from updateIfConditionDemo;

以下是輸出 −

+--------+----------+---------+
| UserId | UserName | UserAge |
+--------+----------+---------+
| 1      | Larry    | 23      |
| 2      | Mike     | 21      |
| 3      | Sam      | 23      |
| 4      | David    | 23      |
| 5      | Maxwell  | 23      |
+--------+----------+---------+
5 rows in set (0.00 sec)

以下是使用 IF 條件進行更新的查詢 −

mysql> update updateIfConditionDemo set UserAge =if(UserAge =23,26,UserAge);
Query OK, 4 rows affected (0.20 sec)
Rows matched: 5 Changed: 4 Warnings: 0

讓我們再次查看錶記錄。UserAge 已從 23 更新為 26 −

mysql> select *from updateIfConditionDemo;

以下是輸出 −

+--------+----------+---------+
| UserId | UserName | UserAge |
+--------+----------+---------+
| 1      | Larry    | 26      |
| 2      | Mike     | 21      |
| 3      | Sam      | 26      |
| 4      | David    | 26      |
| 5      | Maxwell  | 26      |
+--------+----------+---------+
5 rows in set (0.00 sec)

更新於: 30-Jul-2019

9K+ 瀏覽量

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.