cdn网站加速-linux空间-在PostgreSQL中设置表中某列值自增或循环方式

这篇文章首要介绍了cdn网站加速在PostgreSQL中设置表中linux空间某列值自增或循环办法,具有很好的参考价值,期望对我们有所协助。一同跟从小编过来看看吧。

在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循环的写法(与上文无关)

do $$
declare
v_idx integer :=0;
begin
while v_idx < 10 loop
update tb set num = v_idx;
v_idx = v_idx + 1;
end loop;
end $$;

弥补:postgreSQL SQL句子创立自增表

办法一:postgreSQL经过将字段类型设置为serial来将表规划为自增表

CREATE TABLE t_achievement_directory (
id serial8 PRIMARY KEY,
directory_name varchar(255) COLLATE “pg_catalog”.”default”,
pid int8,
modify_time timestamp(6)
)
;

办法二:GENERATED BY ALWAYS AS IDENTITY 或 GENERATED BY DEFAULT AS IDENTITY

1id int8 NOT NULL GENERATED BY DEFAULT AS IDENTITY

1id int8 NOT NULL GENERATED ALWAYS AS IDENTITY

这两种办法的差异在于:

generated always as identity 总是依照(START WITH 1 INCREMENT BY 1)的办法刺进数据,并保护索引。即不允许用户向id列指定数据刺进。

可是 generated by default as identity 则是在用户不指定id列值的情况下依照(START WITH 10 INCREMENT BY 10)办法刺进数据,假如用户指定,则仍然依照指定的值刺进。

共有 0 条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注