首页 > 解决方案 > Postgres:了解主键序列

问题描述

我的数据库不同步,这让我想到了这个问题: 当 postgres 不同步时,如何重置 postgres 的主键序列?(复制如下)

但是,我不太明白这里的一些事情:什么是'your_table_id_seq'?我不知道在哪里可以找到这个。进行了一些挖掘,我发现了一个名为pg_sequence in的表pg_catalog。与此有关吗?不过,我看不到任何方法可以将该数据关联回我的表格。

-- 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;

标签: postgresqlprimary-key

解决方案


以下查询给出了所有序列的名称。

SELECT c.relname 
FROM pg_class c 
WHERE c.relkind = 'S';

通常一个序列被命名为 ${table}_id_seq。

我在这个问题中找到了答案:List all sequences in a Postgres db 8.1 with SQL


推荐阅读