How do I INSERT INTO from one MySQL table into another table and set the value of one column?

MySQLMySQLi Database

Let us first create a table. Following is the query −

mysql> create table insertOneToAnotherTable
   -> (
   -> Value int
   -> );
Query OK, 0 rows affected (0.60 sec)

Following is the query to insert some records in the table using insert command −

mysql> insert into insertOneToAnotherTable values(100);
Query OK, 1 row affected (0.08 sec)

mysql> insert into insertOneToAnotherTable values(200);
Query OK, 1 row affected (0.15 sec)

mysql> insert into insertOneToAnotherTable values(300);
Query OK, 1 row affected (0.13 sec)

mysql> insert into insertOneToAnotherTable values(400);
Query OK, 1 row affected (0.15 sec)

mysql> insert into insertOneToAnotherTable values(500);
Query OK, 1 row affected (0.12 sec)

mysql> insert into insertOneToAnotherTable values(600);
Query OK, 1 row affected (0.16 sec)

Following is the query to display all records from the table using select statement −

mysql> select * from insertOneToAnotherTable;

This will produce the following output −

+-------+
| Value |
+-------+
| 100   |
| 200   |
| 300   |
| 400   |
| 500   |
| 600   |
+-------+
6 rows in set (0.00 sec)

Here is the query to create second table −

mysql> create table recieveDateFromTable
   -> (
   -> Value1 int,
   -> Value2 int
   -> );
Query OK, 0 rows affected (0.83 sec)

Following is the query to INSERT INTO from one MySQL table into another table and set the value of one column −

mysql> insert into recieveDateFromTable(Value1,Value2) select Value,1000 from
insertOneToAnotherTable;
Query OK, 6 rows affected (0.14 sec)
Records: 6 Duplicates: 0 Warnings: 0

Let us display all records from the second table. Following is the query −

mysql> select * from recieveDateFromTable;

This will produce the following output −

+--------+--------+
| Value1 | Value2 |
+--------+--------+
| 100    | 1000   |
| 200    | 1000   |
| 300    | 1000   |
| 400    | 1000   |
| 500    | 1000   |
| 600    | 1000   |
+--------+--------+
6 rows in set (0.00 sec)
raja
Published on 16-Apr-2019 14:54:39
Advertisements