INSERT INTO语句用来给一个table插入信息的records。
语法:
第一种,指定列名和插入的值
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, valu23, ...);
第二种,如果表内的所有列都有,那在SQL查询中就不必指定列的名字。但值的顺序要和表内的列的顺序一致。
INSERT INTO table_name
VALUES (value1, value2, value3, ...)
例子:
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B.Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway')
INSERT INTO SELECT语句将数据从一个表拷贝出来,然后加入到另一个表中。
操作时,要保证拷贝出的数据的类型,和要插入的表的数据类型是匹配的。
此操作对目的表中的其他数据不造成影响。
语法:
将一个表中的所有数据拷贝到另一个表中。
INSERT INTO table2
SELECT * FROM table1
WHERE condition;
将一个表中的几列数据拷贝到另一个表中:
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
举例:
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers;
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
SELECT SupplierName, ContactName, Address, City, PostalCode, Country FROM Suppliers;
将一个Union后的结果,插入一个表:
INSERT INTO Team (name, age)
SELECT customer_name AS name, 21 AS age FROM Customers WHERE customer_id IS NOT NULL
UNION
SELECT customer_name, 31 FROM Orders
ORDER BY name;
从第一个表取得客户名,还有固定数字,第二个表也是,然后组合。然后插入另一个表。
参考:
SQL INSERT INTO SELECT Statement
sql - Insert into with union - Stack Overflow