PostgreSQL標準建表語句分享

如下所示:

-- 建表
CREATE TABLE if not exists public.user
(
 id character varying(32) NOT NULL DEFAULT sys_guid(),
 name character varying(100) NOT NULL,
 gender character varying(50) NOT NULL,
 age character varying(10) NOT NULL,
 id_no character varying(50) NOT NULL,
 created_date timestamp without time zone DEFAULT now(),
 created_by character varying(100) DEFAULT 'system',
 updated_date timestamp without time zone DEFAULT now(),
 update_by character varying(100) DEFAULT 'system',
 CONSTRAINT user_pkey PRIMARY KEY (id)
)with (oids = false);
 
-- 註釋
COMMENT ON TABLE public.user IS '用戶表';
COMMENT ON COLUMN public.user.id IS '主鍵';
COMMENT ON COLUMN public.user.name IS '姓名';
COMMENT ON COLUMN public.user.gender IS '性別';
COMMENT ON COLUMN public.user.age IS '年齡';
COMMENT ON COLUMN public.user.id_no IS '身份證號';
COMMENT ON COLUMN public.user.created_date IS '創建時間';
COMMENT ON COLUMN public.user.created_by IS '創建人';
COMMENT ON COLUMN public.user.updated_date IS '更新時間';
COMMENT ON COLUMN public.user.update_by IS '更新人';
 
-- 主鍵 (如果建表語句裡面沒添加主鍵就執行該語句)
alter table public.user
 add constraint user_pkey primary key (id);
 
-- 索引或唯一索引
drop index if exists user_name;
CREATE INDEX user_name ON user (name);
 
drop index if exists user_id_no;
CREATE UNIQUE INDEX user_id_no ON user (id_no);
 
-- 授權
GRANT ALL ON TABLE public.user TO mydata;
GRANT SELECT, UPDATE, INSERT, DELETE ON TABLE public.user TO mydata_dml;
GRANT SELECT ON TABLE public.user TO mydata_qry;
 

補充:postgresql基本功能:創建表、新增列、修改列字段名稱、某列值自增或循環自增、

根據現有表創建新表:

CREATE TABLE “test04” AS ( select * from testdemo);

修改數據表名:

alter table table_name(表名) rename to new_table_name(新表名)

新增列字段:

ALTER TABLE test04 ADD gid1_type integer;

刪除列字段:

ALTER TABLE test04 DROP COLUMN gid1_type;

修改列字段名稱:

alter table test05 RENAME “gid” TO “id”;

修改列字段類型:

ALTER TABLE test05 ALTER COLUMN “gid” TYPE datatype;

特殊的修改為integer:

alter table table_name(表名) alter column 字段名 type 新字段類型 using to_number(字段名,’9′)

更新字段數據:

update test05 set “gid1_type” = 0 where (“組分類型1” = ‘消防栓’) or (“組分類型1” = ‘水表’) or (“組分類型1” = ‘節點’);

在postgresql中,設置已存在的某列(num)值自增:

//將表tb按name排序,利用row_number() over()查詢序號並將該列命名為rownum,創建新表tb1並將結果保存到該表中
create table tb1 as (select *, row_number() over(order by name) as rownum from tb); 
//根據兩張表共同的字段name,將tb1中rownum對應值更新到tb中num中
update tb set num=(select tb1.rownum from tb1 where tb.name = tb1.name);
//判斷表tb1的存在並刪除表
drop table if exists tb1;

在postgresql中,循環設置已存在的某列(num)值為0-9:

//將表tb按name排序,利用row_number() over()查詢序號並將該列命名為rownum,創建新表tb1並將結果保存到該表中
create table tb1 as (select *, row_number() over(order by name) as rownum from tb); 
//根據兩張表共同的字段name,將tb1中rownum對應值更新到tb中num中,由於為0-9循環自增,則%10
update tb set num=(select tb1.rownum from tb1 where tb.name = tb1.name) % 10;
//判斷表tb1的存在並刪除表
drop table if exists tb1;

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。

推薦閱讀: