PostgreSQL SELECT INTO和INSERT INTO SELECT 两种表复制语句

前端之家收集整理的这篇文章主要介绍了PostgreSQL SELECT INTO和INSERT INTO SELECT 两种表复制语句前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

  SELECT INTO和INSERT INTO SELECT两种表复制语句都可以用来复制表与表之间的数据,但是它们之间也有区别。

1. INSERT INTO FROM语句

 语句形式为:Insert into Table2(field1,field2,…) select value1,value2,… from Table1

 要求目标表Table2必须存在,由于目标表Table2已经存在,所以我们除了插入源表Table1的字段外,还可以插入常量。示例如下:

  1. postgres=# create table tb100(id integer,name character varying);
  2. CREATE TABLE postgres=# create table tb101(id integer,name character varying);
  3. CREATE TABLE postgres=# insert into tb100 select generate_series(1,10),'aa';
  4. INSERT 0 10
  1. postgres=# insert into tb101 select * from tb100 where id<5;
  2. INSERT 0 4 postgres=# select * from tb101;
  3. id | name
  4. ----+------
  5. 1 | aa
  6. 2 | aa
  7. 3 | aa
  8. 4 | aa
  9. (4 rows)

2.SELECT INTO FROM语句

 语句形式为:SELECT vale1,value2 into Table2 from Table1

 要求目标表Table2不存在,因为在插入时会自动创建表Table2,并将Table1中指定字段数据复制到Table2中。示例如下:

  1. postgres=# drop table tb101;
  2. DROP TABLE postgres=# postgres=# select * into tb101 from tb100 where id<5;
  3. SELECT 4 postgres=# postgres=# select * from tb101;
  4. id | name
  5. ----+------
  6. 1 | aa
  7. 2 | aa
  8. 3 | aa
  9. 4 | aa
  10. (4 rows)



参考: http://www.cnblogs.com/freshman0216/archive/2008/08/15/1268316.html

猜你在找的Postgre SQL相关文章