我想强制一个表的自动增量字段的一些值,我尝试了这样:
ALTER TABLE product AUTO_INCREMENT = 1453
AND
ALTER SEQUENCE product RESTART WITH 1453;
ERROR: relation "your_sequence_name" does not exist
我有一个表产品与Id和名称字段
我想强制一个表的自动增量字段的一些值,我尝试了这样:
ALTER TABLE product AUTO_INCREMENT = 1453
AND
ALTER SEQUENCE product RESTART WITH 1453;
ERROR: relation "your_sequence_name" does not exist
我有一个表产品与Id和名称字段
当前回答
为方便浏览者,由评论转换而成
从这条消息中不清楚正确的语法是什么。它是:
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();
要重置自动递增,您必须通过使用以下查询获得您的序列名。
语法:
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;
我不确定以上所有的答案, 如果我没有序列名呢? 如果我不想截断我的表呢?
下面的查询帮助我做到这一点,而不影响现有的数据。
ALTER TABLE <<table_name>>
ALTER COLUMN <<primary_key_column_name>> RESTART SET START 4044;
注意,如果表名带有'_',它将在序列名中被删除。
例如,表名:user_tokens列:id 序列名称:usertokens_id_seq
设置序列计数器:
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 |