INSERT INTO SELECT 语句从一个表复制数据,然后把数据插入到一个已存在的表中。目标表中任何已存在的行都不会受影响。
我们可以从一个表中复制所有的列插入到另一个已存在的表中:
INSERT INTO table2
SELECT * FROM table1;
或者我们可以只复制指定的列插入到另一个已存在的表中:
INSERT INTO table2
(column_name(s))
SELECT column_name(s)
FROM table1;
演示数据库
在本教程中,我们将使用 RUNOOB 样本数据库。
下面是选自 "Websites" 表的数据:
+----+--------------+---------------------------+-------+---------+
+----+--------------+---------------------------+-------+---------+
<table>
<tr>
<th>1</th>
<th>Google</th>
<th>https://www.google.cm/</th>
<th>1</th>
<th>USA</th>
</tr>
<tr>
<td>3</td>
<td>菜鸟教程</td>
<td>http://www.runoob.com/</td>
<td>4689</td>
<td>CN</td>
</tr>
<tr>
<td>4</td>
<td>微博</td>
<td>http://weibo.com/</td>
<td>20</td>
<td>CN</td>
</tr>
<tr>
<td>5</td>
<td>Facebook</td>
<td>https://www.facebook.com/</td>
<td>3</td>
<td>USA</td>
</tr>
<tr>
<td>7</td>
<td>stackoverflow</td>
<td>http://stackoverflow.com/</td>
<td>0</td>
<td>IND</td>
</tr>
</table>
+----+---------------+---------------------------+-------+---------+
下面是 "apps" APP 的数据:
mysql> SELECT * FROM apps;
+----+------------+-------------------------+---------+
+----+------------+-------------------------+---------+
<table>
<tr>
<th>1</th>
<th>QQ APP</th>
<th>http://im.qq.com/</th>
<th>CN</th>
</tr>
<tr>
<td>3</td>
<td>淘宝 APP</td>
<td>https://www.taobao.com/</td>
<td>CN</td>
</tr>
</table>
+----+------------+-------------------------+---------+
3 rows in set (0.00 sec)
复制 "apps" 中的数据插入到 "Websites" 中:
INSERT INTO Websites (name, country)
SELECT app_name, country FROM apps;
只复 id=1 的数据到 "Websites" 中:
INSERT INTO Websites (name, country)
SELECT app_name, country FROM apps
WHERE id=1;
来源:https://www.runoob.com/sql/sql-insert-into-select.html