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;

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。

你可能感兴趣的:(PostgreSQL标准建表语句分享)