在 MySQL 中更新單列中的多行?


要更新單列中的多行,請使用 CASE 語句。我們首先建立一個表 -

mysql> create table updateMultipleRowsDemo
   -> (
   -> StudentId int,
   -> StudentMathScore int
   -> );
Query OK, 0 rows affected (0.63 sec)

以下是使用 insert 命令向表中插入記錄的查詢 -

mysql> insert into updateMultipleRowsDemo values(10001,67);
Query OK, 1 row affected (0.14 sec)
mysql> insert into updateMultipleRowsDemo values(10002,69);
Query OK, 1 row affected (0.15 sec)
mysql> insert into updateMultipleRowsDemo values(10003,89);
Query OK, 1 row affected (0.14 sec)
mysql> insert into updateMultipleRowsDemo values(10004,99);
Query OK, 1 row affected (0.13 sec)
mysql> insert into updateMultipleRowsDemo values(10005,92);
Query OK, 1 row affected (0.13 sec)

以下是使用 select 語句從表中顯示所有記錄的查詢 -

mysql> select * from updateMultipleRowsDemo;

這將生成以下輸出 -

+-----------+------------------+
| StudentId | StudentMathScore |
+-----------+------------------+
| 10001     | 67               |
| 10002     | 69               |
| 10003     | 89               |
| 10004     | 99               |
| 10005     | 92               |
+-----------+------------------+
5 rows in set (0.00 sec)

以下是更新 MySQL 中單列中多行的查詢 -

mysql> UPDATE updateMultipleRowsDemo
   -> SET StudentMathScore= CASE StudentId
   -> WHEN 10001 THEN 45
   -> WHEN 10002 THEN 52
   -> WHEN 10003 THEN 67
   -> END
   -> WHERE StudentId BETWEEN 10001 AND 10003;
Query OK, 3 rows affected (0.19 sec)
Rows matched: 3 Changed: 3 Warnings: 0

我們來檢查一下值是否已更新 -

mysql> select * from updateMultipleRowsDemo;

這將生成以下輸出

+-----------+------------------+
| StudentId | StudentMathScore |
+-----------+------------------+
| 10001     | 45               |
| 10002     | 52               |
| 10003     | 67               |
| 10004     | 99               |
| 10005     | 92               |
+-----------+------------------+
5 rows in set (0.00 sec)

更新於: 30-Jul-2019

3K+ 瀏覽量

啟動你的 事業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.