mysql> insert into t2 (log_time) select now();
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> select * from t2;
+----+----------------------------+
| id | log_time |
+----+----------------------------+
| 1 | 2014-11-27 13:44:12.000000 |
+----+----------------------------+
1 row in set (0.00 sec)
现在来看下PostgreSQL:
原始表结构如下, 包含了一个序列作为主键。
Table "ytt_sql.t1"
Column | Type | Modifiers
----------+-----------------------------+-------------------------------------------------
id | integer | not null default nextval('t1_id_seq'::regclass)
log_time | timestamp without time zone |
Indexes:
"t1_pkey" PRIMARY KEY, btree (id)
用类似的语法create table ... like 来创建副本:
t_girl=# create table t2 (like t1 including all);
CREATE TABLE
Time: 50.035 ms
副本的表结构如下,不过可能发现了一个问题,连同原始表的序列也一起弄过来了,这个太不安全了。
Table "ytt_sql.t2"
Column | Type | Modifiers
----------+-----------------------------+-------------------------------------------------
id | integer | not null default nextval('t1_id_seq'::regclass)
log_time | timestamp without time zone |
Indexes:
"t2_pkey" PRIMARY KEY, btree (id)
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)