2017-08-03 29 views
0

我有postgres中的id列,這是不整數的序列。它有1到3個值,而此列的行數超過100個。我想通過查詢連續地將值分配給4,5,6。這是一個例子,雖然我在表格中有很多記錄。那麼幫助我如何使用查詢增加列值手冊

select id, name from xyz order by id; 

      id | name 
      1 | a 
      2 | b 
      3 | c 
       | d 
       | e 
       | f 

想更新ID列導致

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 
+1

是否要**永久**更新表格,或只是在檢索數據時分配這些值? –

+0

是永久的 – user2638158

+0

行有一些排序標準,其中的id是空的? –

回答

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

查找表中的id的最大可用值爲

Select max(id) from xyz 

假設它的值是3,創建一個序列並將最大值+ 1作爲

CREATE SEQUENCE seq START 4; 

更新空ID使用序列

Update xyz 
SET id = nextval('seq') 
WHERE id IS NULL; 
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; 

請注意,「序列」的ID是no沒有保證,但如果你只想產生一個獨特的價值,這並不重要。