我們可以用 if 條件更新 MySQL 嗎?


你可以用 IF 條件和 CASE 語句更新 MySQL。為此,我們先建立一個表。建立表的查詢 −

mysql> create table UpdateWithIfCondition
   −> (
   −> BookId int,
   −> BookName varchar(200)
   −> );
Query OK, 0 rows affected (0.60 sec)

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

mysql> insert into UpdateWithIfCondition values(1000,'C in Depth');
Query OK, 1 row affected (0.12 sec)

mysql> insert into UpdateWithIfCondition values(1001,'Introduction to Java');
Query OK, 1 row affected (0.14 sec)

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

mysql> select *from UpdateWithIfCondition;

以下是輸出 −

+--------+----------------------+
| BookId | BookName             |
+--------+----------------------+
| 1000   | C in Depth           |
| 1001   | Introduction to Java |
+--------+----------------------+
2 rows in set (0.00 sec)

讓我們使用 if 條件將 ‘C in Depth’ 的值更新為 'Introduction to C',並將 1001 的值更新為 2000。查詢如下 −

mysql> update UpdateWithIfCondition
   −> set BookName = if(BookName = 'C in Depth','Introduction to C',BookName),
   −> BookId = if(BookId = 1001,2000,BookId);
Query OK, 2 rows affected (0.43 sec)
Rows matched: 2 Changed: 2 Warnings: 0

以上,我們已更新了兩個列值。以下是對兩個值是否已更新進行檢查的查詢 −

mysql> select *from UpdateWithIfCondition;

以下是使用 if 成功更新值後顯示的輸出 −

+--------+----------------------+
| BookId | BookName             |
+--------+----------------------+
| 1000   | Introduction to C    |
| 2000   | Introduction to Java |
+--------+----------------------+
2 rows in set (0.00 sec)

更新於: 30-Jul-2019

540 次瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.