如何在 MySQL 中更新一系列记录?
要在 MySQL 中更新一系列记录,你可以使用 BETWEEN。我们首先创建一个表
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Name varchar(20), Age int ); Query OK, 0 rows affected (0.53 sec)
以下是使用 insert 命令在表中插入一些记录的查询
mysql> insert into DemoTable(Name,Age) values('Larry',23); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(Name,Age) values('Sam',24); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable(Name,Age) values('Chris',21); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(Name,Age) values('Carol',25); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(Name,Age) values('David',22); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(Name,Age) values('Robert',26); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(Name,Age) values('John',20); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(Name,Age) values('Mike',27); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(Name,Age) values('Johnny',28); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(Name,Age) values('James',23); Query OK, 1 row affected (0.23 sec)
以下是使用 select 命令从表中显示记录的查询
mysql> select *from DemoTable;
这将生成以下输出
+----+--------+------+ | Id | Name | Age | +----+--------+------+ | 1 | Larry | 23 | | 2 | Sam | 24 | | 3 | Chris | 21 | | 4 | Carol | 25 | | 5 | David | 22 | | 6 | Robert | 26 | | 7 | John | 20 | | 8 | Mike | 27 | | 9 | Johnny | 28 | | 10 | James | 23 | +----+--------+------+ 10 rows in set (0.00 sec)
以下是更新 MySQL 中一系列记录的查询。我们正在将 ID 在 5 到 10 范围内的 Name 更新为"Bob"
mysql> update DemoTable set Name='Bob', Age=23 where Id between 5 AND 10; Query OK, 6 rows affected (0.25 sec) Rows matched: 6 Changed: 6 Warnings: 0
现在,我们来显示所有记录,包括已更新的记录
mysql> select *from DemoTable;
这将生成以下输出
+----+-------+------+ | Id | Name | Age | +----+-------+------+ | 1 | Larry | 23 | | 2 | Sam | 24 | | 3 | Chris | 21 | | 4 | Carol | 25 | | 5 | Bob | 23 | | 6 | Bob | 23 | | 7 | Bob | 23 | | 8 | Bob | 23 | | 9 | Bob | 23 | | 10 | Bob | 23 | +----+-------+------+ 10 rows in set (0.00 sec)
广告