首页 > 代码库 > postgres常用操作

postgres常用操作

1. 创建一张表主键自增

create table region(    id serial PRIMARY KEY,    name character varying(128),    value smallint default 8);#会自动创建 region_seq_id表,drop表region时,会自动将region_seq_id表drop

 

2. 自增字段重新从1开始

# 删除表中的所有行,并使主键重新计数truncate region restart identity;# 或者设置下一条sql插入时的技术起始值select setval(region_seq_id, 1, false)

3. 创建外键

create table user (    id serial primary key,    reg_id integer references region(id),    name character varying(128)    );# 或者create table user (    id serial primary key,    reg_id integer,    name character varying(128),    forien key(reg_id) references region(id));

4. 表修改

# 添加列alter table region add column description text;# 移除列alter table region drop column description text;# 修改列上的默认值alter table region alter column value set default 0;# 移除列的默认值alter table region alter column value drop default;# 修改列的数据类型alter table region alter column value type interger;# 列重命名alter table region rename column value to region_time;# 表重命名alter table region rename to region_time;

 

postgres常用操作