將 MAX(col)+1 插入到 MySQL 表中?


首先讓我們建立一個表 -

mysql> create table DemoTable1484
   -> (
   -> Id int
   -> );
Query OK, 0 rows affected (0.46 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable1484 values(100);
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable1484 values(175);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1484 values(165);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1484 values(145);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1484 values(170);
Query OK, 1 row affected (0.10 sec)

使用 select 語句顯示錶中的所有記錄 -

mysql> select * from DemoTable1484;

這將產生以下輸出 -

+------+
| Id   |
+------+
|  100 |
|  175 |
|  165 |
|  145 |
|  170 |
+------+
5 rows in set (0.00 sec)

以下是對同一張表插入 MAX(col)+1 的查詢 -

mysql> insert into DemoTable1484(Id) select max(Id)+1 from DemoTable1484;
Query OK, 1 row affected (0.20 sec)
Records: 1  Duplicates: 0  Warnings: 0

讓我們再次檢查表記錄 -

mysql> select * from DemoTable1484;

這將產生以下輸出。新值已成功插入 -

+------+
| Id   |
+------+
|  100 |
|  175 |
|  165 |
|  145 |
|  170 |
|  176 |
+------+
6 rows in set (0.00 sec)

更新於: 10-Dec-2019

452 次瀏覽

開啟您的職業生涯

完成課程取得認證

開始
廣告
© . All rights reserved.