在PostgreSQL中分隔整数值

问题描述 投票:1回答:1

我有一个具有唯一int字段的表,该字段当前保存(主要)PostgreSQL数据库中的连续值。

我想更新这些值保持相同的顺序,从最小值开始,但确保这些值间隔一些整数差异。

间距为100的示例:

before | after
-------|-------
   516 |   516
   520 |   616
  1020 |   716
  1021 |   816
  1022 |   916
  1816 |  1016

我尝试用序列解决这个问题,但由于UPDATE无法使用ORDER BY,因此无法找到保持顺序的简单方法。

这是几百个条目的一次性“管家”任务,因此不需要效率。

sql postgresql sql-update sql-order-by
1个回答
1
投票

你可以用PLDO(如果你真的不必再做)这样做。以下是如何使用DO进行演示的演示

-- Temporal table for the demo:
CREATE TEMP TABLE demo (id integer,somecolumn integer);
INSERT INTO demo VALUES
(12,6766),
(22,9003),
(33,8656),
(50,6995),
(69,9151),
(96,9160);
-- DO function, here is where you make the ID change.
DO $$
DECLARE
    new_id integer := NULL;
    row integer := 0;
    rows_count integer := 0;
BEGIN
-- Create a temp table to change the id that will be droped at the end.
-- This table should have the same colums as the original table.
    CREATE TEMP TABLE demo_temp (id integer,somecolumn integer) ON COMMIT DROP;
-- Get the initial id
    new_id := id FROM demo ORDER BY id LIMIT 1;
-- Get the rows count for the loop
    rows_count := COUNT(*) FROM demo;
    LOOP
-- Insert into temp table adding the new id.
-- This loops for every row to make sure you have the same order and data.
        INSERT into demo_temp(id,somecolumn)
        SELECT new_id,somecolumn FROM demo ORDER BY id LIMIT 1 OFFSET row;
-- Adding 100 to id
        new_id := new_id+100;
-- Loop control
        row := row+1;
        EXIT WHEN rows_count = row;
    END LOOP;
-- Clean original table
    TRUNCATE demo;
-- Insert temp table with new id
    INSERT INTO demo(id,somecolumn) SELECT id,somecolumn FROM demo_temp;
END $$;
-- See result:
SELECT * FROM demo;

最后一个选择返回New Table:

New Table:                  Old Table:
id  |  somecolumn           id  |  somecolumn
----+-------------          ----+-------------
12  |  6766                 12  |  6766
112 |  9003                 22  |  9003
212 |  8656                 33  |  8656
312 |  6995                 50  |  6995
412 |  9151                 69  |  9151
512 |  9160                 96  |  9160
© www.soinside.com 2019 - 2024. All rights reserved.