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

ALTER TABLE product AUTO_INCREMENT = 1453

AND

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

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


当前回答

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

TRUNCATE TABLE someTable RESTART IDENTITY;

其他回答

要重置自动递增,您必须通过使用以下查询获得您的序列名。

语法:

SELECT pg_get_serial_sequence(‘tablename’, ‘ columnname‘);

例子:

SELECT pg_get_serial_sequence('demo', 'autoid');

查询将返回autoid的序列名为"Demo_autoid_seq" 然后使用以下查询重置自动id

语法:

ALTER SEQUENCE sequenceName RESTART WITH value;

例子:

ALTER SEQUENCE "Demo_autoid_seq" RESTART WITH 1453;

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

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

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

ALTER SEQUENCE product_id_seq RESTART WITH 1453;

节点脚本:修复所有表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();
-- Change the starting value of the sequence

ALTER SEQUENCE project_id_seq RESTART 3000;

相同但充满活力:

SELECT SETVAL('project_id_seq', (SELECT MAX(id) FROM project));

SELECT的使用很奇怪,但它有效。

来源: https://kylewbanks.com/blog/Adding-or-Modifying-a-PostgreSQL-Sequence-Auto-Increment

编辑:删除+1建议在评论