加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

PostgreSQL中设置表中某列值自增或循环

发布时间:2020-12-13 16:41:30 所属栏目:百科 来源:网络整理
导读:在postgresql中,设置已存在的某列(num)值自增,可以用以下方法: //将表tb按name排序,利用row_number() over()查询序号并将该列命名为rownum,创建新表tb1并将结果保存到该表中create table tb1 as (select *,row_number() over(order by name) as rownum

  在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;

  
  参考内容为https://zhidao.baidu.com/question/390932023437481925.html的最佳答案

其它:附录一个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 $$;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读