PostgreSQL 复制表的 5 种方式详解

 

PostgreSQL 提供了多种不同的复制表的方法,它们的差异在于是否需要复制表结构或者数据。

CREATE TABLE AS SELECT 语句可以用于复制表结构和数据,但是不会复制索引。

我们可以使用以下语句基于 employee 复制一个新表 emp2,包括表中的数据:

1
2
3
CREATE TABLE emp2
AS
SELECT * FROM employee;

如果只想要复制表结构,不复制数据,可以增加 WITH NO DATA 子句:

1
2
3
4
CREATE TABLE emp2
AS
SELECT * FROM employee
WITH NO DATA;

或者也可以使用一个不返回任何结果的查询语句,例如:

1
2
3
4
CREATE TABLE emp2
AS
SELECT * FROM employee
WHERE FALSE;

这种复制方法不会创建任何索引或者约束,例如主键、外键以及 NOT NULL 约束等。

 

CREATE TABLE LIKE 语句

CREATE TABLE LIKE 语句也可以用于复制表结构:

1
2
CREATE TABLE emp3
(LIKE employee);

语法中的括号是必不可少的,而且这种方法不会复制数据,但是会复制字段的 NOT NULL 约束。

CREATE TABLE AS TABLE 语句

CREATE TABLE AS TABLE 语句可以复制表结构和数据,例如:

1
2
3
4
CREATE TABLE emp4
AS
TABLE employee
WITH NO DATA;

这种语法不会复制索引、外键以及非空约束等。

如果不需要复制数据,可以使用 WITH NO DATA 子句:

1
2
3
4
CREATE TABLE emp4
AS
TABLE employee
WITH NO DATA;

SELECT INTO 语句

SELECT INTO 语句可以复制表结构和数据,但是不包含索引等。例如:

1
SELECT * INTO emp5 FROM employee;

PostgreSQL 推荐使用 CREATE TABLE AS 替代 SELECT INTO 语句实现类似效果,因为前者适用性更广,功能更全。

CREATE TABLE INHERITS 语句

PostgreSQL 支持 CREATE TABLE 语句的 INHERIT 子句,用于继承表结构。这种复制表的方法和其他方法有所区别,任何针对父表的修改通常也会自动修改子表。

另外,这种方法还可以为子表定义额外的字段。例如:

1
2
3
4
CREATE TABLE emp5 (
    notes text NOT NULL
)
INHERITS ( employee );

其中,notes 是我们额外定义的字段,其他字段继承 employee。

使用 psql \d 命令查看 emp5 的结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
\d emp5
 
                        Table "public.emp5"
  Column   |          Type          | Collation | Nullable | Default
-----------+------------------------+-----------+----------+---------
 emp_id    | integer                |           | not null |
 emp_name  | character varying(50)  |           | not null |
 sex       | character varying(10)  |           | not null |
 dept_id   | integer                |           | not null |
 manager   | integer                |           |          |
 hire_date | date                   |           | not null |
 job_id    | integer                |           | not null |
 salary    | numeric(8,2)           |           | not null |
 bonus     | numeric(8,2)           |           |          |
 email     | character varying(100) |           | not null |
 notes     | text                   |           | not null |
Check constraints:
    "ck_emp_salary" CHECK (salary > 0::numeric)
    "ck_emp_sex" CHECK (sex::text = ANY (ARRAY['男'::character varying, '女'::character varying]::text[]))
Inherits: employee

 

 

 

 

==========================================================================================

 

SQL数据库中把一个表中的数据复制到另一个表中

 

1、如果是整个表复制表达如下:

insert into table1 select * from table2

2、如果是有选择性的复制数据表达如下:

insert into table1(column1,column2,column3...) select column1,column2,colunm3... from table2

3、一个数据库中的表中的数据复制到另一个数据库中的一个表,使用方法如下:

insert into 数据库A.dbo.table1(col1,col2,col3...) select col1,col2,col3... from 数据库B.dbo.table2

4、创建新表跟原表一样的结构,并复制数据

select * into tableNew from table

posted @   CrossPython  阅读(3049)  评论(1编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示