将 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)
广告