SQL INSERT INTO SELECT 語句
使用SQL,您可以將信息從一個表中復制到另一個表中。
INSERT INTO SELECT 語句從表中復制數(shù)據(jù),并將數(shù)據(jù)插入現(xiàn)有的表中。目標表中的任何現(xiàn)有行都不會受到影響。
SQL INSERT INTO SELECT 語法
我們可以將所有列從一個表中復制到另一個已經(jīng)存在的表中:
INSERT INTO table2
SELECT * FROM table1;
或者我們可以把想要的列復制到另一個現(xiàn)有的表中:
INSERT INTO table2
(column_name(s))
SELECT column_name(s)
FROM table1;
演示數(shù)據(jù)庫
在本教程中,我們將使用著名的Northwind示例數(shù)據(jù)庫。
以下是"Customers"表中的數(shù)據(jù):
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1
|
Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
選自 "Suppliers" 表的數(shù)據(jù):
SupplierID | SupplierName | ContactName | Address | City | Postal Code | Country | Phone |
---|---|---|---|---|---|---|---|
1 | Exotic Liquid | Charlotte Cooper | 49 Gilbert St. | Londona | EC1 4SD | UK | (171) 555-2222 |
2 | New Orleans Cajun Delights | Shelley Burke | P.O. Box 78934 | New Orleans | 70117 | USA | (100) 555-4822 |
3 | Grandma Kelly's Homestead | Regina Murphy | 707 Oxford Rd. | Ann Arbor | 48104 | USA | (313) 555-5735 |
SQL INSERT INTO SELECT 實例
把 "Suppliers" 一欄復制到 "Customers" 一欄:
實例
INSERT INTO Customers (CustomerName, Country)
SELECT SupplierName, Country FROM Suppliers;
SELECT SupplierName, Country FROM Suppliers;
只將德國供應商的副本插入 "Customers" :
實例
INSERT INTO Customers (CustomerName, Country)
SELECT SupplierName, Country FROM Suppliers
WHERE Country='Germany';
SELECT SupplierName, Country FROM Suppliers
WHERE Country='Germany';
更多建議: