Perform complex MySQL insert by using CONCAT()?

MySQLMySQLi Database

To perform complex MySQL insert, you can use CONCAT() function. Let us see an example and create a table with StudentId and StudentFirstName.

After that, complex MySQL insert will be performed and 'Web Student’ text will get inserted for every value and unique StudentId will get concatenated.

The query to create first table is as follows −

mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentFirstName varchar(20)
);
Query OK, 0 rows affected (0.55 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(StudentFirstName) values('John');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTableStudentFirstName) values('Larry');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(StudentFirstName) values('Bob');
Query OK, 1 row affected (0.13 sec)

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

mysql> select *from DemoTable;

This will produce the following output −

+-----------+------------------+
| StudentId | StudentFirstName |
+-----------+------------------+
| 1         | John             |
| 2         | Larry            |
| 3         | Bob              |
+-----------+------------------+
3 rows in set (0.00 sec)

Here is the query to create second table which is as follows −

mysql> create table DemoTable2
(
   ClientId int,
   ClientProjectName varchar(20)
);
Query OK, 0 rows affected (0.54 sec)

Following is the complex MySQL insert −

mysql> insert into DemoTable2 select StudentId,concat('Web Student=', StudentId) from DemoTable;
Query OK, 3 rows affected (0.17 sec)
Records : 3 Duplicates : 0 Warnings : 0

Display all records from the second table using select statement −

mysql> select *from DemoTable2;

This will produce the following output −

+----------+-------------------+
| ClientId | ClientProjectName |
+----------+-------------------+
| 1        | Web Student=1     |
| 2        | Web Student=2     |
| 3        | Web Student=3     |
+----------+-------------------+
3 rows in set (0.00 sec)
raja
Published on 29-Apr-2019 07:26:32
Advertisements