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