A single MySQL query to select value from first table and insert in the second?

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable1(
   Value int
);
Query OK, 0 rows affected (0.65 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(67);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1 values(46);
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

+-------+
| Value |
+-------+
| 67    |
| 46    |
+-------+
2 rows in set (0.00 sec)

Following is the query to create the second table −

mysql> create table DemoTable2(
   Score int
);
Query OK, 0 rows affected (0.70 sec)

Following is how you can insert record in the second table from the first table −

mysql> insert into DemoTable2(Score) select Value from DemoTable1;
Query OK, 2 rows affected (0.13 sec)
Records: 2 Duplicates: 0 Warnings: 0

Display all records from the table using select statement −

mysql> select *from DemoTable2;

This will produce the following output −

+-------+
| Score |
+-------+
| 67    |
| 46    |
+-------+
2 rows in set (0.00 sec)
raja
Published on 27-Sep-2019 07:34:03
Advertisements