我们能否使用单次 MySQL 查询来更新具有最高 ID 的行?
是的,我们可以做到。我们首先创建一个表格 -
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)
广告