postgresql 提供了多种不同的复制表的方法,它们的差异在于是否需要复制表结构或者数据。
create table as select 语句
create table as select 语句可以用于复制表结构和数据,但是不会复制索引。
我们可以使用以下语句基于 employee 复制一个新表 emp2,包括表中的数据:
create table emp2 as select * from employee;
如果只想要复制表结构,不复制数据,可以增加 with no data 子句:
create table emp2 as select * from employee with no data;
或者也可以使用一个不返回任何结果的查询语句,例如:
create table emp2 as select * from employee where false;
这种复制方法不会创建任何索引或者约束,例如主键、外键以及 not null 约束等。
create table like 语句
create table like 语句也可以用于复制表结构:
create table emp3 (like employee);
语法中的括号是必不可少的,而且这种方法不会复制数据,但是会复制字段的 not null 约束。
create table as table 语句
create table as table 语句可以复制表结构和数据,例如:
create table emp4 as table employee with no data;
这种语法不会复制索引、外键以及非空约束等。
如果不需要复制数据,可以使用 with no data 子句:
create table emp4 as table employee with no data;
select into 语句
select into 语句可以复制表结构和数据,但是不包含索引等。例如:
select * into emp5 from employee;
postgresql 推荐使用 create table as 替代 select into 语句实现类似效果,因为前者适用性更广,功能更全。
create table inherits 语句
postgresql 支持 create table 语句的 inherit 子句,用于继承表结构。这种复制表的方法和其他方法有所区别,任何针对父表的修改通常也会自动修改子表。
另外,这种方法还可以为子表定义额外的字段。例如:
create table emp5 ( notes text not null ) inherits ( employee );
其中,notes 是我们额外定义的字段,其他字段继承 employee。
使用 psql \d 命令查看 emp5 的结构如下:
\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
到此这篇关于postgresql 复制表的 5 种方式的文章就介绍到这了,更多相关postgresql 复制表内容请搜索七九推以前的文章或继续浏览下面的相关文章希望大家以后多多支持七九推!
发表评论