postgresql 截断表后序列不会重置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13989243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sequence does not reset after truncating the table
提问by user1369887
I use SELECT lastval() to get wrong serial id after truncated the table.
截断表后,我使用 SELECT lastval() 得到错误的序列号。
when I truncate the table, I use SELECT lastval(), I got the wrong ID/
当我截断表时,我使用 SELECT lastval(),我得到了错误的 ID/
回答by Igor Romanchenko
回答by Eric Wang
Following is the standard way to reset sequence:
以下是重置序列的标准方法:
truncate table table_name restart identity;
but in some version & platform, it's syntax error,
但在某些版本和平台中,这是语法错误,
in that case, you can truncate without reset sequence, and alter the sequence with another sql, try this:
在这种情况下,您可以在不重置序列的情况下截断,并使用另一个 sql 更改序列,试试这个:
truncate table table_name;
alter sequence seq_name start 1;
回答by jahmed31
The best way to reset a sequence to start back with number 1 is to execute the following after you have successfully truncate it:
重置序列以从数字 1 开始的最佳方法是在成功截断它后执行以下操作:
ALTER SEQUENCE <tablename>_<id>_seq RESTART WITH 1
So, for example for the users table it would be:
因此,例如对于用户表,它将是:
ALTER SEQUENCE users_id_seq RESTART WITH 1
回答by Daniel Gastón
Check the next
检查下一个
ALTER SEQUENCE sequence_name RESTART WITH 1;
回答by Clodoaldo Neto
If you want to reset the sequence then:
如果要重置序列,则:
setval('sequence_name', 0)
To list the existent sequence names issue a \ds
at the psql prompt.
要列出现有的序列名称\ds
,请在 psql 提示符下发出 a 。
回答by 5a01d01P
Try this:
尝试这个:
TRUNCATE TABLE table_name RESTART IDENTITY CASCADE;
TRUNCATE TABLE table_name RESTART IDENTITY CASCADE;