使用 CONCAT() 執行復雜 MySQL 插入?


要執行復雜的 MySQL 插入,可以使用 CONCAT() 函式。讓我們看一個示例並建立一個包含 StudentId 和 StudentFirstName 的表。

之後,將執行復雜的 MySQL 插入,併為每個值插入“Web Student”文字,且唯一的 StudentId 會被連線。

以下是建立第一個表的查詢 -

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

使用 insert 命令向表中插入一些記錄 -

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 語句從表中顯示所有記錄的查詢 -

mysql> select *from DemoTable;

這會生成以下輸出 -

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

以下是建立第二個表的查詢 -

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

以下是複雜的 MySQL 插入 -

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 語句顯示第二個表中的所有記錄 -

mysql> select *from DemoTable2;

這會生成以下輸出 -

+----------+-------------------+
| ClientId | ClientProjectName |
+----------+-------------------+
| 1        | Web Student=1     |
| 2        | Web Student=2     |
| 3        | Web Student=3     |
+----------+-------------------+
3 rows in set (0.00 sec)

更新於: 30-Jul-2019

超過 1 千次瀏覽

啟動您的 事業

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.