如何基於 MySQL 中的條件替換記錄?


若要設定條件,請使用 MySQL CASE 語句。我們首先來建立一個 –

mysql> create table DemoTable1481
   -> (
   -> PlayerScore int
   -> );
Query OK, 0 rows affected (0.42 sec)

使用 insert 向表中插入一些記錄 –

mysql> insert into DemoTable1481 values(454);
Query OK, 1 row affected (0.41 sec)
mysql> insert into DemoTable1481 values(765);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1481 values(890);
Query OK, 1 row affected (0.09 sec)

使用 select 顯示錶中的所有記錄 –

mysql> select * from DemoTable1481;

這將會產生以下輸出 –

+-------------+
| PlayerScore |
+-------------+
|         454 |
|         765 |
|         890 |
+-------------+
3 rows in set (0.00 sec)

以下是用於替換 MySQL 中記錄的查詢 –

mysql> update DemoTable1481
   -> set PlayerScore= case when PlayerScore=454 then 1256
   -> when PlayerScore=765 then 1865
   -> when PlayerScore=890 then 3990
   -> end
   -> ;
Query OK, 3 rows affected (0.17 sec)
Rows matched: 3  Changed: 3 Warnings: 0

讓我們再次檢查表記錄 –

mysql> select * from DemoTable1481;

這將會產生以下輸出 –

+-------------+
| PlayerScore |
+-------------+
|        1256 |
|        1865 |
|        3990 |
+-------------+
3 rows in set (0.00 sec)

更新於: 12-Nov-2019

682 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告