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

ALTER TABLE product AUTO_INCREMENT = 1453

AND

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

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


当前回答

节点脚本:修复所有表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();

其他回答

节点脚本:修复所有表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();

如果您使用id列创建了表product,那么序列就不是简单地称为product,而是product_id_seq(即${table}_${column}_seq)。

这是你需要的ALTER SEQUENCE命令:

ALTER SEQUENCE product_id_seq RESTART WITH 1453

您可以使用psql中的\ds命令查看数据库中的序列。如果您执行\d product并查看列的默认约束,那么nextval(…)调用也将指定序列名。

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

语法:

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;

设置序列计数器:

setval('product_id_seq', 1453);

如果你不知道序列名,使用pg_get_serial_sequence函数:

select pg_get_serial_sequence('product', 'id');
 pg_get_serial_sequence 
------------------------
 public.product_id_seq

参数是表名和列名。

或者只是在psql提示符下发出一个\d product:

=> \d product
                         Table "public.product"
 Column |  Type   |                      Modifiers                       
--------+---------+------------------------------------------------------
 id     | integer | not null default nextval('product_id_seq'::regclass)
 name   | text    | 

获取序列id使用

SELECT pg_get_serial_sequence('tableName', 'ColumnName');

这将为您提供序列id tableName_ColumnName_seq

要获得最后的种子数量使用

select currval(pg_get_serial_sequence('tableName', 'ColumnName'));

或者如果你知道序列id已经直接使用它。

select currval(tableName_ColumnName_seq);

它会告诉你最后的种子号

重置种子数量使用

ALTER SEQUENCE tableName_ColumnName_seq RESTART WITH 45