如何创建 PostgreSQL 前导零序列 (zerofill)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6862766/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-20 23:10:27  来源:igfitidea点击:

How to Create PostgreSQL Leading Zero Sequence (zerofill)

postgresqlzerofill

提问by Vasilen Donchev

How can I create a leading zero sequence in PostgreSQL?

如何在 PostgreSQL 中创建前导零序列?

For MySQL I know it is BIGINT(10) UNSIGNED ZEROFILL AUTO_INCREMENTbut in PostgreSQL I can't find an equivalent (only bigserial).

对于 MySQL,我知道它是,BIGINT(10) UNSIGNED ZEROFILL AUTO_INCREMENT但在 PostgreSQL 中我找不到等效的(仅bigserial)。

Moreover how can I limit the number of zeroes as BIGINT(10)means 10 symbols, does the type bigserialhave such a limit?

此外,如何将零的数量限制为BIGINT(10)10 个符号,类型bigserial是否有这样的限制?

回答by Andrey

A good alternative to to_char()in a "fill leading zeros" task is lpad():

to_char()“填充前导零”任务的一个很好的替代方法是lpad()

create table TableName(columnName serial primary key);

select lpad(columnName::text, 3, '0'), * from TableName;

Caution: lpad()does not generate an error on overflow, see for example:

注意:lpad()在溢出时不会产生错误,请参见示例:

select lpad(4444::text, 3, '0'), to_char(4444, '000')

回答by m1tk4

Create a regular sequence, then use to_char() to pad it with leading zeroes. Your data type will be char(), though, Postgres does not support zerofill for integral types.

创建一个常规序列,然后使用 to_char() 用前导零填充它。您的数据类型将是 char(),但 Postgres 不支持整数类型的 zerofill。