Fetch maximum ID value from the first table and insert to all the IDs in another table with MySQL INSERT INTO select?


Let us first create a table −

mysql> create table DemoTable1
(
   Id int,
   Name varchar(100)
);
Query OK, 0 rows affected (0.86 sec)

Insert some records in the table using insert command −

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)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

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

Following is the query to create the second table −

mysql> create table DemoTable2
(
   StudentId int,
   StudentFirstName varchar(100)
);
Query OK, 0 rows affected (1.15 sec)

Insert some records in the table using insert command. Here, we have inserted the maximum ID value from the first table to the StudentID column of the second table −

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

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

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

Updated on: 01-Oct-2019

365 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements