我想要随机播放(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890)并从1到6获取子字符串。
我已经尝试了很多,但无法在postgres中找到一个随机播放功能
update tablename
set secureno=substring(shuffle(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890) from 1 for 6)
答案 0 :(得分:1)
您可以使用此查询随机播放字符串:
select substr('ABCD', i, 1)
from generate_series(1, 4) i
order by random();
substr
--------
B
C
A
D
(4 rows)
将它用于你的密钥(有62个字符),得到6个字符并聚合成字符串:
select string_agg(ch, '')
from (
select substr('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890', i, 1) ch
from generate_series(1, 62) i
order by random()
limit 6
) s
如果您经常需要这个::
,可以根据算法创建一个函数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
$$;
select left(shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'), 6);
答案 1 :(得分:0)
这样就可以了:
SELECT string_agg(c, '')
FROM (SELECT c
FROM regexp_split_to_table(
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890',
''
) c
ORDER BY random()
LIMIT 6
) AS q;