如何在MySQL中使用单个WHERE子句更新多行?
为此,您可以使用MySQLIN()
。让我们首先创建一个-
mysql> create table DemoTable1420 -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> FirstName varchar(20), -> LastName varchar(20), -> Age int -> );
使用insert在表中插入一些记录-
mysql> insert into DemoTable1420(FirstName,LastName,Age) values('Chris','Brown',23); mysql> insert into DemoTable1420(FirstName,LastName,Age) values('David','Miller',22); mysql> insert into DemoTable1420(FirstName,LastName,Age) values('John','Smith',24); mysql> insert into DemoTable1420(FirstName,LastName,Age) values('John','Doe',21); mysql> insert into DemoTable1420(FirstName,LastName,Age) values('Adam','Smith',25);
使用选择显示表中的所有记录-
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); 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)