如何在 MySQL 中使用單個 WHERE 子句更新多行?


對此,你可以使用 MySQL IN()。首先讓我們建立一個 -

mysql> create table DemoTable1420
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> FirstName varchar(20),
   -> LastName varchar(20),
   -> Age int
   -> );
Query OK, 0 rows affected (1.12 sec)

使用 insert 在表中插入一些記錄 -

mysql> insert into DemoTable1420(FirstName,LastName,Age) values('Chris','Brown',23);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1420(FirstName,LastName,Age) values('David','Miller',22);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1420(FirstName,LastName,Age) values('John','Smith',24);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1420(FirstName,LastName,Age) values('John','Doe',21);
Query OK, 1 row affected (0.43 sec)
mysql> insert into DemoTable1420(FirstName,LastName,Age) values('Adam','Smith',25);
Query OK, 1 row affected (0.18 sec)

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

mysql> select * from DemoTable1420;

將產生以下輸出 -

+----+-----------+----------+------+
| Id | FirstName | LastName | Age  |
+----+-----------+----------+------+
|  1 | Chris     | Brown    |   23 |
|  2 | David     | Miller   |   22 |
|  3 | John      | Smith    |   24 |
|  4 | John      | Doe      |   21 |
|  5 | Adam      | Smith    |   25 |
+----+-----------+----------+------+
5 rows in set (0.00 sec)

下面的查詢使用單個 where 子句更新多行 -

mysql> update DemoTable1420
   -> set FirstName='Carol',LastName='Taylor'
   -> where Id IN(1,3,4,5);
Query OK, 4 rows affected (0.42 sec)
Rows matched: 4  Changed: 4 Warnings: 0

讓我們再次檢查表記錄 -

mysql> select * from DemoTable1420;

將產生以下輸出 -

+----+-----------+----------+------+
| Id | FirstName | LastName | Age  |
+----+-----------+----------+------+
|  1 | Carol     | Taylor   | 23   |
|  2 | David     | Miller   | 22   |
|  3 | Carol     | Taylor   | 24   |
|  4 | Carol     | Taylor   | 21   |
|  5 | Carol     | Taylor   | 25   |
+----+-----------+----------+------+
5 rows in set (0.00 sec)

更新於: 12-Nov-2019

856 次瀏覽

開啟你的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.