如何使用函数在PostgreSQL中生成随机唯一数 [英] How to generate random unique number in PostgreSQL using function
问题描述
在PostgreSQL中,如何为列生成
且在表列中不存在的随机唯一整数?
In PostgreSQL, how to generate random unique integer number for column, return which not exits in table column?
推荐答案
请参见 pseudo_encrypt 函数,该函数基于 Feistel网络技术。结合postgres序列,可以保证结果的唯一性以及人眼的随机性。
See the pseudo_encrypt function, which implements a permutation based on the Feistel network technique. Combined with a postgres sequence, this guarantees unicity of the result, as well as randomness to the human eye.
示例:
create sequence seq maxvalue 2147483647;
create table tablename(
id bigint default pseudo_encrypt(nextval('seq')::int),
[other columns]
);
此处 id
的有效范围是 0 ... 2 ^ 32-1
。如有必要,可以通过修改功能进行调整。可以在以下位置找到具有64位输出空间的变体: pseudo_encrypt()在plpgsql中使用bigint 函数。
The effective range of id
here is 0...2^32-1
. This can be adjusted if necessary by modifying the function. A variant with a 64 bits output space can be found at: pseudo_encrypt() function in plpgsql that takes bigint.
编辑: pseudo_encrypt
仅实现一个排列,并且不接受用户提供的密钥。如果您希望根据私钥进行自己的排列,则可以考虑 skip32
(基于Skipjack的32位分组密码,具有10个字节宽的密钥)。
pseudo_encrypt
implements only one permutation, and it does not accept a user-supplied key. If you prefer having your own permutations, depending on secret keys, you may consider skip32
(a 32-bit block cipher based on Skipjack, with 10 bytes wide keys).
可从以下位置使用plpgsql函数(从Perl / C移植):
https://wiki.postgresql.org/wiki/Skip32
A plpgsql function (ported from Perl/C) is available at: https://wiki.postgresql.org/wiki/Skip32
这篇关于如何使用函数在PostgreSQL中生成随机唯一数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!