我想强制一个表的自动增量字段的一些值,我尝试了这样:

ALTER TABLE product AUTO_INCREMENT = 1453

AND

ALTER SEQUENCE product  RESTART WITH 1453;
ERROR:  relation "your_sequence_name" does not exist

我有一个表产品与Id和名称字段


当前回答

要将其设置为下一个最大值,您可以使用:

SELECT SETVAL(pg_get_serial_sequence('table_name', 'column_name'), (SELECT MAX(column_name) FROM table_name));

其他回答

节点脚本:修复所有表identity: auto-increment / nextval,基于上次插入它。

const pg = require('pg');
const { Client } = pg;

const updateTables = async () => {

  const client = new Client({
    user: 'postgres',
    host: 'localhost',
    database: 'my-database',
    password: 'postgres',
    port: 5432,
  });

  await client.connect();

  console.log('Connected');

  const execQuery = async (queryStr, params = []) => {
    return new Promise((resolve, reject) => {
      client.query(queryStr, params, (error, results) => {
        if (error) {
          reject(error);
        } else {
          resolve(results);
        }
      })
    })
  }

  const tablesRes = await execQuery(`
    SELECT table_name
    FROM information_schema.tables
    WHERE table_type='BASE TABLE'
    AND table_schema='public';
  `)

  const tables = tablesRes.rows.map(row => row.table_name);

  tables.map(async tableName => {
    let lastId;
    try {
      const res = await execQuery(`SELECT id from "${tableName}" ORDER BY id DESC LIMIT 1`);
      lastId = res.rows[0].id;
    } catch (e) {}

    if (lastId) {
      const nextId = lastId + 1;
      const queryStr = `ALTER SEQUENCE ${tableName}_id_seq RESTART WITH ${nextId}`;
      await execQuery(queryStr);
      console.log(tableName, queryStr);
    }
  })

};

updateTables();

下面是你要找的命令,假设你的product表序列是product_id_seq:

ALTER SEQUENCE product_id_seq RESTART WITH 1453;

如果表格是这样的

bigint NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 0)

插入0-9范围内的记录后,会导致下次插入时发生冲突,因此重置START:

ALTER TABLE ... ALTER COLUMN ... RESTART WITH 10;

下面的命令会自动执行此操作:这也会删除表中的所有数据。所以要小心。

TRUNCATE TABLE someTable RESTART IDENTITY;

使用这个查询来检查什么是序列键与模式和表,

SELECT pg_get_serial_sequence('"SchemaName"."TableName"', 'KeyColumnName'); // output: "SequenceKey"

使用这个查询逐个增加增量值,

SELECT nextval('"SchemaName"."SequenceKey"'::regclass); // output 110

当插入到下一个表时,增量值将被用作键(111)。

使用此查询将特定值设置为增量值

SELECT setval('"SchemaName"."SequenceKey"', 120);

当插入到下一个表时,增量值将被用作键(121)。