2017-08-03 12 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 
    4 | d 
    5 | e 
    6 | f 

を引き起こす

select id, name from xyz order by id; 

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

が欲しかったクエリでidカラムを更新するために私を助けて、それを考慮しないでください。

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はnullですか? –

答えて

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 

はあなたが単一でこれを行うことができ

Update xyz 
SET id = nextval('seq') 
WHERE id IS NULL; 
0

としてシーケンスを使用して

CREATE SEQUENCE seq START 4; 

アップデート空のidとしての価値3.シーケンスを作成してに最大値+ 1を代入されていると仮定します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の「シーケンス」は「いいえ」です一意の値を生成したいだけなら問題はありません。