INSERT INTO SELECT 語句
作用
INSERT INTO SELECT 語法 用於將一個表複製到另一個表。
語法(在insert語句中嵌套select語句)
<-- table1是目標表,table2是源表(即要將該表指定列數據插入目標表中的表) -->
INSERT INTO table1 (column_1, column_2, column_3) SELECT column_1, column_2, column_3 FROM table2;
或
INSERT INTO table1 SELECT column_1, column_2, column_3 FROM table2;
提示
第一條語句
- 源表和目錄表的字段數目一致或不一致時,都適用。但需要保證目標表和源表的對應字段的數據類型必須一致。
- 例如: table1_column_1字段的數據類型爲varchar,則table2_column_1字段的數據類型也要爲varchar。不能table1_column_1字段數據類型爲varchar,而table2_column_1字段的數據類型爲int。
第二條語句
- 使用於源表和目標表的字段數目一致 或 源表的字段數目多於目標表的字段數目。且也需要保證目標表和源表的對應字段的數據類型必須一致。
演示數據庫
student表
mysql> select *from student;
+--------------+-----+-----+-----------+------+
| student_name | age | sex | specialty | addr |
+--------------+-----+-----+-----------+------+
| 三娘 | 25 | 女 | 計算機 | 深圳 |
| 四叔 | 24 | 男 | 軟件技術 | 廣州 |
| 五嬸 | 20 | 女 | 商務英語 | 上海 |
+--------------+-----+-----+-----------+------+
3 rows in set
assistant表
mysql> select *from assistant;
+----------------+------+------+
| assistant_name | age | sex |
+----------------+------+------+
| NULL | NULL | NULL |
| 三娘 | 25 | 女 |
| 四叔 | 24 | 男 |
+----------------+------+------+
3 rows in set
1 row in set
示例
需求: 年齡在24歲及以上的學生可以申請當助教,統計student表中有多少個學生有資格申請當助教,並將他們的姓名、年齡、性別存到assistant表中。
mysql> select *from student;
+--------------+-----+-----+-----------+------+
| student_name | age | sex | specialty | addr |
+--------------+-----+-----+-----------+------+
| 三娘 | 25 | 女 | 計算機 | 深圳 |
| 四叔 | 24 | 男 | 軟件技術 | 廣州 |
| 五嬸 | 20 | 女 | 商務英語 | 上海 |
+--------------+-----+-----+-----------+------+
3 rows in set
mysql> select *from assistant;
+----------------+------+------+
| assistant_name | age | sex |
+----------------+------+------+
| NULL | NULL | NULL |
+----------------+------+------+
1 row in set
<--- 將teacher表的student_name,age,sex三個字段的數據 複製到 assistant表的assistant_name,age,sex三個字段中 -->
mysql> insert into assistant(assistant_name,age,sex) select student_name,age,sex from student where age>=21;
Query OK, 2 rows affected
Records: 2 Duplicates: 0 Warnings: 0
mysql> select *from assistant;
+----------------+------+------+
| assistant_name | age | sex |
+----------------+------+------+
| NULL | NULL | NULL |
| 三娘 | 25 | 女 |
| 四叔 | 24 | 男 |
+----------------+------+------+
3 rows in set