如何在现有的顺序自动递增值序列之间插入间隔?

时间:2018-11-07 07:09:06

标签: postgresql insert unique

我的表test定义为:

CREATE TABLE test
(
    id        BIGSERIAL PRIMARY KEY,
    val       TEXT
);

按顺序有英语句子。 id从1开始自动递增:

select id, val from test;
 id  |             val              
-----+------------------------------
  1  | Dr. Livesey, and the rest of these gentlemen having
  2  | asked me to write down the whole
  3  | particulars about Treasure Island, from
  4  | the beginning to the end, keeping nothing
  5  | back but the bearings of the island, and
  6  | that only because there is still treasure 
  7  | not yet lifted, I take up my pen in the year
  8  | of grace 17__ and go back to the time when my father
  9  | kept the Admiral Benbow inn and the
 10  | brown old seaman with the sabre cut
 11  | first took up his lodging under our roof
...
 999 | in my ears: “Pieces of eight! Pieces of eight

假设表很大。如果要在第5行和6行之间插入新句子,则必须从第6行开始增加所有id的行。我的目标是:

 id  |             val              
-----+------------------------------
  1  | Dr. Livesey, and the rest of these gentlemen having
  2  | asked me to write down the whole
  3  | particulars about Treasure Island, from
  4  | the beginning to the end, keeping nothing
  5  | back but the bearings of the island, and
  7  | that only because there is still treasure 
  8  | not yet lifted, I take up my pen in the year

允许我使用id = 6插入新行。但是Postgres似乎尝试从上至下更新ID,导致:

=> update test set id = id + 1 where id > 5;
ERROR:  duplicate key value violates unique constraint "test_pkey"
DETAIL:  Key (id)=(7) already exists.

我可以告诉Postgres从下至上开始更新吗?

0 个答案:

没有答案