PostgreSQL快速创建空表TIPS(二)

2015-01-24 01:46:11 · 作者: · 浏览: 11
?
?
?
?
不过我这里LIKE了所有选项,也可以不不包括默认值,这样,序列本身就不会复制进来了。
?
t_girl=# create table t2 (like t1 including all excluding defaults);  
CREATE TABLE  
Time: 40.292 ms  
??
                 Table "ytt_sql.t2"  
  Column  |            Type             | Modifiers   
----------+-----------------------------+-----------  
 id       | integer                     | not null  
 log_time | timestamp without time zone |   
Indexes:  
    "t2_pkey" PRIMARY KEY, btree (id)  

?

?
?
这里也可以不用LIKE 选项,直接用类似CREATE TABLE AS ...语法,如下:
创建没有记录的空表,但是这里只包含了表结构以及字段相关。
?
t_girl=# create table t2 as table t1 with no data;  
SELECT 0  
Time: 15.562 ms  
或者  
t_girl=# create table t2 as select * from t1 where false;  
SELECT 0  
Time: 14.181 ms  

?

?
?
?
?
我们手动给添加主键以及默认值。
?
t_girl=# alter table t2 add constraint pk_t2_id primary key (id), alter id set default nextval('t2_id_seq');  
ALTER TABLE  
Time: 41.105 ms 
?
?
?
结构跟原来一样了。
                                    Table "ytt_sql.t2"  
  Column  |            Type             |                    Modifiers                      
----------+-----------------------------+-------------------------------------------------  
 id       | integer                     | not null default nextval('t2_id_seq'::regclass)  
 log_time | timestamp without time zone |   
Indexes:  
    "pk_t2_id" PRIMARY KEY, btree (id)  

?