我们想要一个函数,它的参数是三个字节的bytea类型(由pgcrypto扩展的函数gen_random_bytes生成),该函数返回一个随机的6位整数(介于0和999999之间,包括0和999999)。6位数的整数应该保留传递给函数的参数所给出的随机性。
发布于 2018-04-30 19:27:38
我可能过于复杂了,但我需要确保字符串中恰好有n个数字。允许数字重复。
SELECT string_agg(shuffle('0123456789')::char, '')
FROM generate_series(1, 6);为了方便起见,我在这里复制了another answer中提供的随机播放函数
create or replace function shuffle(text)
returns text language sql as $$
select string_agg(ch, '')
from (
select substr($1, i, 1) ch
from generate_series(1, length($1)) i
order by random()
) s
$$;发布于 2017-06-27 01:49:09
如果是3个字节,取最后6个字符,在前面加上'x',转换为位串,然后转换为整数:
select ('x' || right(gen_random_bytes(3)::text, 6))::bit(24)::int;更多细节在类似的问题中:What's the easiest way to represent a bytea as a single integer in PostgreSQL?
https://stackoverflow.com/questions/44763839
复制相似问题