SELECT INTO和INSERT INTO SELECT兩種表復(fù)制語句都可以用來復(fù)制表與表之間的數(shù)據(jù)投蝉,但是它們之間也有區(qū)別。
1. INSERT INTO FROM語句
語句形式為:Insert into Table2(field1,field2,…) select value1,value2,… from Table1
要求目標(biāo)表Table2必須存在从铲,由于目標(biāo)表Table2已經(jīng)存在澜建,所以我們除了插入源表Table1的字段外米丘,還可以插入常量。示例如下:
postgres=# create table tb100(id integer,name character varying);
CREATE TABLE
postgres=# create table tb101(id integer,name character varying);
CREATE TABLE
postgres=# insert into tb100 select generate_series(1,10),'aa';
INSERT 0 10
123456789
postgres=# insert into tb101 select * from tb100 where id<5;
INSERT 0 4
postgres=# select * from tb101;
id | name
----+------
1 | aa
2 | aa
3 | aa
4 | aa
(4 rows)1234567891011
2.SELECT INTO FROM語句
語句形式為:SELECT vale1, value2 into Table2 from Table1
要求目標(biāo)表Table2不存在秧骑,因?yàn)樵诓迦霑r(shí)會(huì)自動(dòng)創(chuàng)建表Table2版确,并將Table1中指定字段數(shù)據(jù)復(fù)制到Table2中。示例如下:
postgres=# drop table tb101;
DROP TABLE
postgres=#
postgres=# select * into tb101 from tb100 where id<5;
SELECT 4
postgres=#
postgres=# select * from tb101;
id | name
----+------
1 | aa
2 | aa
3 | aa
4 | aa
(4 rows)1234567891011121314