Insert values from the first table to the second table using two SELECT statements in a single MySQL query

MySQLMySQLi Database

To insert values from the first table to another table using two SELECT statements, use SUBQUERY. This will allow you to use only a single MySQL query to get the result in the second table. Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values('Chris',45);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1 values('Bob',78);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1 values('David',98);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1 values('Carol',89);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

+-------+-------+
| Name  | Score |
+-------+-------+
| Chris |    45 |
| Bob   |    78 |
| David |    98 |
| Carol |    89 |
+-------+-------+
4 rows in set (0.00 sec)

Following is the query to create the second table.

mysql> create table DemoTable2
(
   StudentName varchar(100),
   StudentScore int
);
Query OK, 0 rows affected (0.58 sec)

Let us now write a MySQL query to insert values from the first table to the second table using two SELECT statements −

mysql> insert into DemoTable2(StudentName,StudentScore) values((select Name from DemoTable1 where Score=98),(select Score from DemoTable1 where Name='David'));
Query OK, 1 row affected (0.30 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2;
+-------------+--------------+
| StudentName | StudentScore |
+-------------+--------------+
| David       |           98 |
+-------------+--------------+
1 row in set (0.00 sec)
raja
Published on 24-Sep-2019 16:36:51
Advertisements