从第一个表中获取最大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)
热门推荐
8 入学校简短祝福语
10 恩师退休花束祝福语简短
11 给男生的简短祝福语
12 员工对同事祝福语简短
13 高中升学宴祝福语简短
14 七一祝福语明信片文案简短
15 公司文案生日祝福语简短
16 英文写结婚祝福语简短
17 送给同桌的祝福语简短
18 科研文案祝福语简短励志