How to add a row to a table using only strings from another table as reference in MySQL?

MySQLMySQLi Database

For this, use INSERT INTO SELECT statement in MySQL. Let us create a table −

mysql> create table demo61
−> (
−> id int,
−> name varchar(20)
−> )
−> ;
Query OK, 0 rows affected (1.84 sec)

Insert some records into the table with the help of insert command −

mysql> insert into demo61 values(1,'John');
Query OK, 1 row affected (0.63 sec)

mysql> insert into demo61 values(2,'David');
Query OK, 1 row affected (0.13 sec)

mysql> insert into demo61 values(1,'Mike');
Query OK, 1 row affected (0.10 sec)

mysql> insert into demo61 values(2,'Carol');
Query OK, 1 row affected (0.30 sec)

mysql> insert into demo61 values(2,'Bob');
Query OK, 1 row affected (0.09 sec)

Display records from the table using select statement −

mysql> select *from demo61;

This will produce the following output −

+------+-------+
| id   | name  |
+------+-------+
|    1 | John  |
|    2 | David |
|    1 | Mike  |
|    2 | Carol |
|    2 | Bob   |
+------+-------+
5 rows in set (0.00 sec)

Following is the query to create second table.

mysql> create table demo62
-> (
−> employee_id int not null auto_increment primary key,
−> employee_name varchar(20)
−> );
Query OK, 0 rows affected (1.60 sec)

Insert some records into the table with the help of insert command −

mysql> insert into demo62(employee_name)
−> select name from demo61 where id=2;
Query OK, 3 rows affected (0.14 sec)
Records: 3 Duplicates: 0 Warnings: 0

Display records from the table using select statement −

mysql> select *from demo62;

This will produce the following output −

+-------------+---------------+
| employee_id | employee_name |
+-------------+---------------+
| 1           | David         |
| 2           | Carol         |
| 3           | Bob           |
+-------------+---------------+
3 rows in set (0.00 sec)
raja
Published on 20-Nov-2020 11:45:24
Advertisements