Perform complex MySQL insert by using CONCAT()?
要执行复杂的MySQL插入,可以使用CONCAT()函数。 让我们看一个示例,并使用StudentId和StudentFirstName创建一个表。
之后,将执行复杂的MySQL插入操作,并为每个值插入" Web Student"文本,并连接唯一的StudentId。
创建第一个表的查询如下-
1 2 3 4 5 6 | mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentFirstName varchar(20) ); Query OK, 0 rows affected (0.55 sec) |
使用insert命令在表中插入一些记录-
1 2 3 4 5 6 | 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) |
以下是使用select语句显示表中所有记录的查询-
1 | mysql> select *from DemoTable; |
这将产生以下输出-
1 2 3 4 5 6 7 8 | +-----------+------------------+ | StudentId | StudentFirstName | +-----------+------------------+ | 1 | John | | 2 | Larry | | 3 | Bob | +-----------+------------------+ 3 rows in set (0.00 sec) |
这是创建第二个表的查询,如下所示:
1 2 3 4 5 6 | mysql> create table DemoTable2 ( ClientId int, ClientProjectName varchar(20) ); Query OK, 0 rows affected (0.54 sec) |
以下是复杂的MySQL插入-
1 2 3 | 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 |
使用select语句显示第二个表中的所有记录-
1 | mysql> select *from DemoTable2; |
这将产生以下输出-
1 2 3 4 5 6 7 8 | +----------+-------------------+ | ClientId | ClientProjectName | +----------+-------------------+ | 1 | Web Student=1 | | 2 | Web Student=2 | | 3 | Web Student=3 | +----------+-------------------+ 3 rows in set (0.00 sec) |