insert into select 语法
INSERT INTO SELECT 语句从一个表复制数据,然后把数据插入到一个已存在的表中。
目标表中任何已存在的行都不会受影响。
我们可以从一个table1表中复制所有的列插入到另一个已存在的table2表中:
INSERT INTO table2
SELECT * FROM table1;
或者我们可以只复制希望的列插入到另一个已存在的表中:
INSERT INTO table2
(column_name(s))
SELECT column_name(s)
FROM table1;
演示数据库
在猿变手册教程中,我们将使用 yuanbian 样本数据库。
下面是选自 "articles" 表的数据:
+----+-----------------+-----------+--------+---------------------+
| id | title | author | a_type | pub_date |
+----+-----------------+-----------+--------+---------------------+
| 1 | hadoop简介 | 大猿 | 311 | 2003-01-05 11:23:00 |
| 2 | python元类 | 小猿 | 163 | 2003-01-11 13:00:01 |
| 3 | HTML基础 | 猿大头 | 497 | 2004-03-09 12:00:00 |
| 4 | Javascript | 猿媛 | 20 | 2005-11-03 17:34:12 |
| 5 | ETL快速入门 | 猿媛 | 3 | 2005-11-07 18:40:00 |
| 6 | 异步编程 | 大猿 | 3 | 2005-11-07 18:45:00 |
+----+-----------------+-----------+--------+---------------------+
下面是 "downloads" 数据:
+----+-----------------------------+-------------------+--------+------------+
| id | title | url | author | pub_date |
+----+-----------------------------+-------------------+--------+------------+
| 1 | 快速搭建自己的web | http://******/120 | 大猿 | 2021-01-03 |
| 2 | 一分钟搞定人脸识别 | http://******/121 | 小猿 | 2021-01-03 |
+----+-----------------------------+-------------------+--------+------------+
insert into select 示例
全表复制
复制 "downloads" 中的数据插入到 "articles" 中:
INSERT INTO articles
(title, author, pub_date)
SELECT title, author, pub_date
FROM downloads;
执行结果
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0
WHERE筛选复制
只复制指定author "大猿"的资源到 "articles" 中:
INSERT INTO articles
(title, author, pub_date)
SELECT title, author, pub_date
FROM downloads
WHERE author='大猿';
执行结果
Query OK, 1 row affected (0.35 sec)
Records: 1 Duplicates: 0 Warnings: 0
讨论区