我们是否可以用单个MySQL查询更新具有最高ID的行?
是的,我们可以这样做。让我们首先创建一个表 –
mysql> create table DemoTable
(
ID int,
GameScore int
);
Query OK, 0 rows affected (0.55 sec)
使用插入命令将一些记录插入表中 –
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;
阅读更多:MySQL 教程
输出
+------+-----------+
| ID | GameScore |
+------+-----------+
| 15 | 848747 |
| 13 | 909049 |
| 34 | 98474646 |
| 31 | 948474 |
+------+-----------+
4行(0.00秒)
以下是使用单个查询更新具有最高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行(0.00秒)
极客教程