将 PostgreSQL 主键重置为 1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3819292/
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-10 22:41:03  来源:igfitidea点击:

Reset PostgreSQL primary key to 1

postgresqlprimary-keyreset

提问by David

Is there a way to reset the primary key of a PostgreSQL table to start at 1 again on a populated table?

有没有办法将 PostgreSQL 表的主键重置为在填充表上再次从 1 开始?

Right now it's generating numbers from 1000000 and up. I want it all to reset and start to 1, keeping all my existing data intact.

现在它正在生成 1000000 及以上的数字。我希望这一切都重置并从 1 开始,同时保持我所有现有的数据完好无损。

采纳答案by Vinko Vrsalovic

Primary keys that autoincrement (i.e., columns with data type serial primary key) are associated with a sequence. You can set the next value for any sequence using the setval(<seqname>, <next_value>)function. Note that to actually execute the function by itself you need to use SELECT, like this: SELECT setval(<seqname>, <next_value>)

自动递增的主键(即数据类型serial primary key为 的列)与序列相关联。您可以使用该setval(<seqname>, <next_value>)函数为任何序列设置下一个值。请注意,要自己实际执行该函数,您需要使用SELECT,如下所示:SELECT setval(<seqname>, <next_value>)

The name of the auto created sequences when using serial are <table>_<column>_seq

使用串行时自动创建的序列的名称是 <table>_<column>_seq

回答by Pawe? Go?cicki

The best way to reset a sequence to start back with number 1 is to execute the following:

重置序列以从数字 1 开始的最佳方法是执行以下操作:

ALTER SEQUENCE <tablename>_<id>_seq RESTART WITH 1

So, for example for the userstable it would be:

因此,例如对于users表,它将是:

ALTER SEQUENCE users_id_seq RESTART WITH 1

回答by ROQUEFORT Fran?ois

@bluish actually inserting a new record using an auto-incremented primary key, is just like using a sequence explicitly this way:

@bluish 实际上使用自动递增的主键插入新记录,就像以这种方式显式使用序列一样:

INSERT INTO MyTable (id, col1, ...) VALUES (MySeq.nextval(), val1, ...)

So, if you want the first id to be 1, you should have to set your sequence to 0. But it's out of bounds, so you must use the ALTER SEQUECE statement. So, if you have a serial field named number in your table menu, for exemple:

因此,如果您希望第一个 id 为 1,则必须将序列设置为 0。但它越界了,因此您必须使用 ALTER SEQUECE 语句。因此,如果您的表格菜单中有一个名为 number 的序列字段,例如:

ALTER SEQUENCE menu_number_seq RESTART

will make the job perfectly.

将使工作完美。