我有一个带有唯一int字段的表,该字段当前保存(主要)PostgreSQL数据库中的连续值。
我想更新这些值,保持相同的顺序,从最小值开始,但要确保这些值间隔一些整数差异。
间距为100的示例:
before | after
-------|-------
516 | 516
520 | 616
1020 | 716
1021 | 816
1022 | 916
1816 | 1016
我尝试使用序列解决此问题,但由于UPDATE
无法使用ORDER BY
,因此无法找到一种简单的方法来保持订单。
这是一次性的家务管理'任务为几百个条目,因此不需要效率。
答案 0 :(得分:1)
您可以使用PL
或DO
执行此操作(如果您不必再次执行此操作)。以下是使用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: 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