如何重置postgres主键序列时不同步? [英] How to reset postgres' primary key sequence when it falls out of sync?

查看:183
本文介绍了如何重置postgres主键序列时不同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了问题,我的主键序列与我的表行不同步。



也就是说,当我插入一个新行时,我得到一个重复的键错误,因为序列数据类型中隐含的序列返回一个已经存在的数字。

$

解决方案

   - 登录到psql并运行以下
- 结果是什么?
SELECT MAX(id)FROM your_table;

- 然后运行...
- 这应该高于最后的结果。
SELECT nextval('your_table_id_seq');

- 如果不高于...运行这个设置序列最后到您的最高pid它。
- (明智地运行一个快速pg_dump首先...)
SELECT setval('your_table_id_seq',(SELECT MAX(id)FROM your_table));
- 如果你的表没有行
- false表示下一个nextval()调用
返回的值set setval('your_table_id_seq',COALESCE(SELECT MAX (id)+1 FROM your_table),1),false);

来源 - Ruby论坛


I ran into the problem that my primary key sequence is not in sync with my table rows.

That is, when I insert a new row I get a duplicate key error because the sequence implied in the serial datatype returns a number that already exists.

It seems to be caused by import/restores not maintaining the sequence properly.

解决方案

-- Login to psql and run the following
-- What is the result?
SELECT MAX(id) FROM your_table;

-- Then run...
-- This should be higher than the last result.
SELECT nextval('your_table_id_seq');

-- If it's not higher... run this set the sequence last to your highest pid it. 
-- (wise to run a quick pg_dump first...)
SELECT setval('your_table_id_seq', (SELECT MAX(id) FROM your_table));
-- if your tables might have no rows
-- false means the set value will be returned by the next nextval() call    
SELECT setval('your_table_id_seq', COALESCE((SELECT MAX(id)+1 FROM your_table), 1), false);

Source - Ruby Forum

这篇关于如何重置postgres主键序列时不同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆