我們能否使用單次 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)

更新於: 30-Jul-2019

191 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.