插入 MySQL 選擇的結果?是否可行?


每次插入select結果時,都無需使用值。要插入select的結果,我們首先建立兩個表。

第一個表查詢如下:

< FirstTableDemo>
mysql> create table FirstTableDemo
   −> (
   −> StudentId int,
   −> StudentName varchar(100)
   −> );
Query OK, 0 rows affected (0.41 sec)

現在建立第二個表,然後使用INSERT SELECT命令將第二個表記錄插入第一個表中。

建立第二個表的查詢:

<SecondTableDemo>

mysql> create table SecondTableDemo
   −> (
   −> Id int,
   −> Name varchar(100)
   −> );
Query OK, 0 rows affected (0.47 sec)

使用insert命令在表中插入記錄。查詢如下:

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

mysql> insert into SecondTableDemo values(2,'Sam');
Query OK, 1 row affected (0.27 sec)

現在我們第二個表中有兩條記錄。使用select語句顯示錶中所有記錄的查詢如下:

mysql> select *from SecondTableDemo;

以下是輸出:

+------+------+
| Id   | Name |
+------+------+
|    1 | John |
|    2 | Sam  |
+------+------+
2 rows in set (0.00 sec)

使用INSERT SELECT語句將第二個表的所有記錄插入第一個表中:

mysql> insert into FirstTableDemo(StudentId,StudentName)
   −> select Id,Name from SecondTableDemo as tbl1
   −> where tbl1.Id not in (select StudentId from FirstTableDemo);
Query OK, 2 rows affected (0.57 sec)
Records: 2 Duplicates: 0 Warnings: 0

現在我們已將第二個表的所有記錄插入第一個表。讓我們使用select語句進行交叉檢查。查詢如下:

mysql> select *from FirstTableDemo;

以下是輸出:

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         1 | John        |
|         2 | Sam         |
+-----------+-------------+
2 rows in set (0.00 sec)

更新於: 2019年7月30日

103 次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.