从第一个表中获取最大ID值,然后使用MySQL INSERT INTO select插入另一个表中的所有ID。

让我们首先创建一个表-

mysql> create table DemoTable1
(
   Id int,
   Name varchar(100)
);

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable1 values(1001,'Chris');
mysql> insert into DemoTable1 values(999,'Robert');
mysql> insert into DemoTable1 values(1003,'Mike');
mysql> insert into DemoTable1 values(1002,'Sam');

使用select语句显示表中的所有记录-

mysql> select *from DemoTable1;

这将产生以下输出-

+------+--------+
| Id   | Name   |
+------+--------+
| 1001 | Chris  |
| 999  | Robert |
| 1003 | Mike   |
| 1002 | Sam    |
+------+--------+
4 rows in set (0.00 sec)

以下是创建第二个表的查询-

mysql> create table DemoTable2
(
   StudentId int,
   StudentFirstName varchar(100)
);

使用insert命令在表中插入一些记录。在这里,我们将最大ID值从第一个表插入到第二个表的StudentID列中-

mysql> insert into DemoTable2(StudentId,StudentFirstName)
   select
   (select Max(Id) from DemoTable1),
   Name from DemoTable1;
Records: 4 Duplicates: 0 Warnings: 0

使用select语句显示表中的所有记录-

mysql> select *from DemoTable1;

这将产生以下输出-

+-----------+------------------+
| StudentId | StudentFirstName |
+-----------+------------------+
|      1003 | Chris            |
|      1003 | Robert           |
|      1003 | Mike             |
|      1003 | Sam              |
+-----------+------------------+
4 rows in set (0.00 sec)
猜你喜欢