我有一个表,它有一个唯一的int字段,当前在PostgreSQL数据库中保存(主要是)连续的值。
我想更新这些值,保持相同的顺序,从最小值开始,但要确保这些值之间有一些整数差。
间距为100的示例:
before | after
-------|-------
516 | 516
520 | 616
1020 | 716
1021 | 816
1022 | 916
1816 | 1016
我试着用序列来解决这个问题,但是找不到一个简单的方法来保持顺序,因为
UPDATE
不能使用ORDER BY
。这是一个一次性的“家政”任务,有几百个条目,所以不需要效率。
最佳答案
您可以使用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
关于sql - 在PostgreSQL中间隔整数值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48077048/