如何在 MySQL 中更新一系列记录?

mysqlmysqli database

要在 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)

相关文章