PostgreSQL
 sql >> Base de Dados >  >> RDS >> PostgreSQL

PostgreSQL, arraste e troque


Exemplo 1:
update kalksad1 set brred=_brred
from (
  select
    row_number() over (
      order by brred<2 desc, brred=4 desc, brred>=2 desc, brred
    ) as _brred,
    kalk_id as _kalk_id
  from kalksad1
  where brkalk=2
  order by _kalk_id
) as _
where kalk_id=_kalk_id and brred!=_brred;

Exemplo 2:
update kalksad1 set brred=_brred
from (
  select
    row_number() over (
      order by brred<4 desc, brred!=1 desc, brred>=4 desc, brred
    ) as _brred,
    kalk_id as _kalk_id
  from kalksad1
  where brkalk=2
  order by _kalk_id
) as _
where kalk_id=_kalk_id and brred!=_brred;

Se você tiver um índice exclusivo em (brkalk,brred) então seria mais complicado, pois durante a renumeração haverá brred duplicado .

Mas para muitas linhas eu recomendaria usar algo que era muito útil nos dias da linguagem BASIC em computadores de 8 bits - numere suas linhas com lacunas.

Então, em vez de:
(26, 2, 1, 'text index 26 doc 2 row 1'),
(30, 2, 2, 'text index 30 doc 2 row 2'),
(42, 2, 3, 'text index 42 doc 2 row 3'),
(43, 2, 4, 'text index 43 doc 2 row 4'),
(12, 2, 5, 'text index 12 doc 2 row 5'),

usar:
(26, 2, 1024, 'text index 26 doc 2 row 1'),
(30, 2, 2048, 'text index 30 doc 2 row 2'),
(42, 2, 3072, 'text index 42 doc 2 row 3'),
(43, 2, 4096, 'text index 43 doc 2 row 4'),
(12, 2, 5120, 'text index 12 doc 2 row 5'),

Então seus exemplos ficariam assim:


  • Exemplo 1:update kalksad1 set brred=(2048+1024)/2 where kalk_id=43 , que mudaria para:
    (26, 2, 1024, 'text index 26 doc 2 row 1'),
    (43, 2, 1536, 'text index 43 doc 2 row 4'),
    (30, 2, 2048, 'text index 30 doc 2 row 2'),
    (42, 2, 3072, 'text index 42 doc 2 row 3'),
    (12, 2, 5120, 'text index 12 doc 2 row 5'),
    


  • Exemplo 2:update kalksad1 set brred=(4096+3072)/2 where kalk_id=43 , que mudaria para:
    (30, 2, 2048, 'text index 30 doc 2 row 2'),
    (42, 2, 3072, 'text index 42 doc 2 row 3'),
    (26, 2, 3584, 'text index 26 doc 2 row 1'),
    (43, 2, 4096, 'text index 43 doc 2 row 4'),
    (12, 2, 5120, 'text index 12 doc 2 row 5'),
    



    Somente quando não há espaço entre as linhas onde o destino deveria estar, você precisa primeiro renumerar as linhas usando, por exemplo:
    update kalksad1 set brred=_brred*1024
    from (
      select row_number() over (order by brred) as _brred, kalk_id as _kalk_id
      from kalksad1
      where brkalk=2
      order by _brred desc
    ) as _
    where kalk_id=_kalk_id;
    

    Isso seria muito melhor do que alterar todas as linhas entre a origem e o destino. Mas isso só importará quando houver muitas linhas a serem alteradas.