不同步时如何重置 Postgres 的主键序列?

新手上路,请多包涵

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

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

这似乎是由于导入/恢复没有正确维护顺序引起的。

原文由 meleyal 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 964
2 个回答
-- 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 id.
-- (wise to run a quick pg_dump first...)

BEGIN;
-- protect against concurrent inserts while you update the counter
LOCK TABLE your_table IN EXCLUSIVE MODE;
-- Update the sequence
SELECT setval('your_table_id_seq', COALESCE((SELECT MAX(id)+1 FROM your_table), 1), false);
COMMIT;

来源 - Ruby 论坛

原文由 meleyal 发布,翻译遵循 CC BY-SA 3.0 许可协议

我找不到 Rails 的明确答案。

rails console

 ActiveRecord::Base.connection.execute("SELECT setval(pg_get_serial_sequence('table_name', 'id'), MAX(id)) FROM table_name;")

例如,将 table_name 替换为 --- users

原文由 NemyaNation 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题