更改串行的起始值 - Postgresql

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16362930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 00:10:25  来源:igfitidea点击:

Change the starting value of a serial - Postgresql

postgresql

提问by afk

I've a little problem with serial : From a file, I filled my database in which I have a client ID (it is a serial and it is my primary key). I have 300 clients so 300 client ID (1 to 300). Now my problem is, I've a form for new clients.I cannot add them because when I add a client, my program adds the client with ID 1 or the ID 1 is already assigned to another client.

我有一个串行的小问题:从一个文件中,我填充了我的数据库,其中有一个客户端 ID(它是一个串行,它是我的主键)。我有 300 个客户,所以有 300 个客户 ID(1 到 300)。现在我的问题是,我有一个新客户的表单。我无法添加它们,因为当我添加一个客户时,我的程序会添加 ID 为 1 的客户,或者 ID 1 已经分配给另一个客户。

So my question is : is it possible to change the starting value of a serial for to resolve this problem ?

所以我的问题是:是否可以更改串行的起始值来解决此问题?

回答by Joachim Isaksson

You can alter a sequence using RESTART WITHto change the current sequence number;

您可以使用RESTART WITH更改当前序列号来更改序列;

ALTER SEQUENCE test_seq RESTART WITH 300;

To get the sequence name if you created it using the serial keyword, use

如果使用 serial 关键字创建序列名称,要获取序列名称,请使用

SELECT adsrc FROM pg_attrdef WHERE adrelid = (SELECT oid FROM pg_class WHERE relname = 'table name goes here'); 

An SQLfiddle to test with.

一个用于测试的 SQLfiddle

回答by Hugh_Kelley

The solutions above did not work for what I needed.

上面的解决方案对我所需要的不起作用。

I needed a serial id to use as a primary key that started from 1000, rather than 1.

我需要一个序列 id 用作从 1000 开始的主键,而不是 1。

In order to do this, I created a standard serial column:

为了做到这一点,我创建了一个标准的串行列:

ALTER table my_table ADD COLUMN new_id SERIAL PRIMARY KEY;

and then updated that column:

然后更新该列:

UPDATE my_table set new_id = new_id + 1000;

I then joined that table to the table with existing non-consecutive id numbers under 1000.

然后,我将该表与现有的非连续 ID 号低于 1000 的表连接在一起。