单个 MySQL 查询仅更新范围内的特定记录而不更新整个列

mysqlmysqli database更新于 2024/4/4 6:11:00

首先我们创建一个表 −

mysql> create table DemoTable
(
   Name varchar(40),
   Position int
);
Query OK, 0 rows affected (1.17 sec)

使用 insert 插入命令在表中插入一些记录 −

mysql> insert into DemoTable values('Chris',90);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values('David',67);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('Bob',55);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('Sam',40);
Query OK, 1 row affected (0.15 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

这将产生以下输出 −

+-------+----------+
| Name  | Position |
+-------+----------+
| Chris |       90 |
| David |       67 |
| Bob   |       55 |
| Sam   |       40 |
+-------+----------+
4 rows in set (0.00 sec)

以下查询仅更新范围内的特定记录而不更新整个列 −

mysql> update DemoTable
   set Position=Position+10
   where Position > 50 and Position < 90;
Query OK, 2 rows affected (0.11 sec)
Rows matched : 2 Changed : 2 Warnings : 0

让我们再次检查表记录 −

mysql> select *from DemoTable;

这将产生以下输出 −

+-------+----------+
| Name  | Position |
+-------+----------+
| Chris |       90 |
| David |       77 |
| Bob   |       65 |
| Sam   |       40 |
+-------+----------+
4 rows in set (0.00 sec)


相关文章