所以我在表中有一个类型为 int 的数组列。我正在对一百万行进行负载测试,每条记录需要四个数组元素,所有元素都具有不同的值。
INSERT INTO contacts (numbers)
SELECT '{4443331111, 2223334444, 2223339999, 8887779999}'
FROM generate_series(1,2) AS x(id);
这会创建 2 条记录,但我需要数字是唯一的。
最佳答案
你需要的是 random()
函数,乘以一些合适的数字得到你的最大值;但是您需要从对该函数的四次调用中构建一个数组。
构造数组值的语法略有不同,在这里使用起来会更容易,如下所示:
SELECT ARRAY[4443331111, 2223334444, 2223339999, 8887779999]
由于您不需要将其构建为字符串,因此您可以对数组的各个部分使用函数调用,这意味着这应该可行:
SELECT ARRAY[random() * 1000000, random() * 1000000, random() * 1000000, random() * 1000000]
FROM generate_series(1,2) AS x(id);
由于 random()
返回一个 float ,而您需要一个整数,因此您需要在某处进行强制转换。最容易编写的是在末尾使用 ::int[]
转换整个数组,如下所示:
SELECT ARRAY[random() * 1000000, random() * 1000000, random() * 1000000, random() * 1000000]::int[]
FROM generate_series(1,2) AS x(id);
Postgres 文档:random()
; array constructors (including note on the casting shortcut)
关于arrays - postgres将随机数插入数组列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16322368/