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;

猜你喜欢

转载自blog.csdn.net/zsc201825/article/details/84285446