我们能否在单个 MySQL 查询中更新 ID 最高的行?

mysqlmysqli database更新于 2025/7/19 21:00:17

是的,可以这样做。让我们首先创建一个表 −

mysql> create table DemoTable
   (
   ID int,
   GameScore int
   );
Query OK, 0 rows affected (0.55 sec)

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

mysql> insert into DemoTable values(15,848747);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(13,909049);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(34,98474646);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(31,948474);
Query OK, 1 row affected (0.27 sec)

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

mysql> select *from DemoTable;

输出

+------+-----------+
| ID   | GameScore |
+------+-----------+
| 15   | 848747    |
| 13   | 909049    |
| 34   | 98474646  |
| 31   | 948474    |
+------+-----------+
4 rows in set (0.00 sec)

以下是在单个查询中更新具有最高 ID 的行的查询 −

mysql> update DemoTable set GameScore=GameScore+10 ORDER BY ID DESC LIMIT 1;
Query OK, 1 row affected (0.19 sec)
Rows matched : 1 Changed : 1 Warnings : 0

让我们再次检查表记录 −

mysql> select *from DemoTable;

输出

+------+-----------+
| ID   | GameScore |
+------+-----------+
| 15   | 848747    |
| 13   | 909049    |
| 34   | 98474656  |
| 31   | 948474    |
+------+-----------+
4 rows in set (0.00 sec)


相关文章


有用资源