postgres create table as select & create table like

來源:互聯網
上載者:User

 1. 準備

  先建立一個基礎資料表:

create table mytb1(id serial,name character varying,age integer);
  在name欄位上建立索引:

create index mytb1_name_index on mytb1(name);

  查看mytb1的表結構:   

postgres=# \d mytb1;                              Table "public.mytb1" Column |       Type        |                     Modifiers                      --------+-------------------+--------------------------------------------------- id     | integer           | not null default nextval('mytb1_id_seq'::regclass) name   | character varying |  age    | integer           | Indexes:    "mytb1_name_index" btree (name)

  插入兩條記錄:

postgres=# insert into mytb1(name,age) values('zhangsan',12),('lisi',23);

 2. 使用created table as select

postgres=# create table mytb2 as select * from mytb1;SELECT 2
  查看mytb2的表結構及表中的資料:

postgres=# \d mytb2          Table "public.mytb2" Column |       Type        | Modifiers --------+-------------------+----------- id     | integer           |  name   | character varying |  age    | integer           | 

postgres=# select * from mytb2; id |   name   | age ----+----------+-----  1 | zhangsan |  12  2 | lisi     |  23(2 rows)
可以看到,使用create table as select ,表中的資料會全部複製過去,表結構中的主鍵,索引,約束等都沒有移過去,僅僅是欄位複製過去。

3. 使用create table like 

postgres=# create table mytb3 (like mytb1);CREATE TABLE
  查看mytb3的表結構及表中的資料:
postgres=# \d mytb3          Table "public.mytb3" Column |       Type        | Modifiers --------+-------------------+----------- id     | integer           | not null name   | character varying |  age    | integer           | 
postgres=# select * from mytb3; id | name | age ----+------+-----(0 rows)
表結構中的索引主鍵也沒有一起過來。

create table like的時候通過including來包含索引,約束等。

postgres=# create table mytb5 (like mytb1 including defaults including constraints including indexes);CREATE TABLE
看看錶結構

postgres=# \d mytb5                              Table "public.mytb5" Column |       Type        |                     Modifiers                      --------+-------------------+--------------------------------------------------- id     | integer           | not null default nextval('mytb1_id_seq'::regclass) name   | character varying |  age    | integer           | Indexes:    "mytb5_name_idx" btree (name)
現在索引,約束等都全部複製過來。


結論:

create table as select : 只會複製表中的資料,表結構中的索引,約束等不會複製過來。

create table like: 不複製資料,需要複製索引,約束等還要自己including進去。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.