從第一個表中獲取最大 ID 值並使用 MySQL INSERT INTO select 插入到另一個表中的所有 ID?
讓我們首先建立一個表 −
mysql> create table DemoTable1 ( Id int, Name varchar(100) ); Query OK, 0 rows affected (0.86 sec)
使用 insert 命令在表中插入一些記錄 −
mysql> insert into DemoTable1 values(1001,'Chris'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1 values(999,'Robert'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1 values(1003,'Mike'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable1 values(1002,'Sam'); Query OK, 1 row affected (0.13 sec)
使用 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) ); Query OK, 0 rows affected (1.15 sec)
使用 insert 命令在表中插入一些記錄。我們在這裡將第一個表中的最大 ID 值插入到第二個表的 StudentID 列中 −
mysql> insert into DemoTable2(StudentId,StudentFirstName) select (select Max(Id) from DemoTable1), Name from DemoTable1; Query OK, 4 rows affected (0.20 sec) 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)
廣告