Computer >> Computer tutorials >  >> Programming >> MySQL

MySQL INSERT INTO SELECT resulting in multiple rows inserted at once from another table


Let us first create a table −

mysql> create table DemoTable(Name varchar(100));
Query OK, 0 rows affected (0.55 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values('Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1 values('Robert');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1 values('Adam');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1 values('Bob');
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

+--------+
| Name   |
+--------+
| Chris  |
| Robert |
| Adam   |
| Bob    |
+--------+
4 rows in set (0.00 sec)

Following is the query to create second table.

mysql> create table DemoTable2(ListOfEmployee text);
Query OK, 0 rows affected (0.59 sec)

Following is the query to perform INSERT INTO SELECT resulting in multiple rows inserted −

mysql> insert into DemoTable2(ListOfEmployee) select group_concat(Name) from DemoTable1;
Query OK, 1 row affected (0.20 sec)
Records − 1 Duplicates − 0 Warnings − 0

Display all records from the table using select statement −

mysql> select *from DemoTable2;

This will produce the following output −

+-----------------------+
| ListOfEmployee        |
+-----------------------+
| Chris,Robert,Adam,Bob |
+-----------------------+
1 row in set (0.00 sec)