我在postgres中有id列,它不是整数的串行。它有1到3个值,而此列的行超过100.我想通过查询不断地将值分配给空行为4,5,6。这是一个例子,虽然我在表中有很多记录。所以帮助我如何使用查询更新id列
select id, name from xyz order by id;
id | name
1 | a
2 | b
3 | c
| d
| e
| f
想要的结果
select id, name from xyz order by id;
id | name
1 | a
2 | b
3 | c
4 | d
5 | e
6 | f
以下仅针对提交问题的行,请不要考虑:
select id ,name,date_time,(select 'wasa'::text) as link from abc
union
select x.id+max(a.id),x.name,x.date_time,(select 'uu'::text) as link from xyz x ,abc a
group by x.id
order by id
答案 0 :(得分:0)
select count(id) into temp_count
from table_name ;
select id into temp_id
from table_name order by id asc limit 1;
while (temp_id <=temp_count)
Do
set temp_last_id = (select id from table_name where id is not null order by id desc limit 1);
update table_name
set id = temp_last_id +1;
set temp_id =temp_id +1;
end while;
答案 1 :(得分:0)
从表中查找id的最大可用值
Select max(id) from xyz
假设其值为3.创建序列并将最大值+ 1分配为
CREATE SEQUENCE seq START 4;
使用序列
更新空IDUpdate xyz
SET id = nextval('seq')
WHERE id IS NULL;
答案 2 :(得分:0)
您可以使用一个update
语句执行此操作:
update xyz
set id = t.rn
from (
select ctid,
row_number() over (order by name) + (select count(*) from xyz where id is not null) as rn
from xyz
where xyz.id is null
) t
where t.ctid = xyz.ctid;
请注意&#34;序列&#34; ID无法保证,但如果您只想生成一个唯一值,则无关紧要。