PostgreSQL循环随机插入 [英] PostgreSQL loop with random inserts
问题描述
我在db中有一个表:
CREATE TABLE operation ( <br>
id integer NOT NULL DEFAULT NEXTVAL ('seq_operation'),( <br>
phone_number varchar(30),( <br>
age integer,( <br>
gender char(1),( <br>
isActive boolean,( <br>
date_of_surgery timestamp,( <br>
);
我需要插入10000行随机数据,如何制作这样的INSERT语句呢?我对此很新鲜,并试图通过其他答案来解决类似的问题,但找不到对我来说容易理解的一个。
I need to insert 10000 rows with random data. How can I make such INSERT statement? Im fresh with this stuff and trying to figure it out with other answers for similiar question here, but cant find easy understandable one for me.
非常感谢您的帮助。
最诚挚的问候,
Max
Best regards, Max
推荐答案
我通常使用的是psql:
I usually use something like this is psql:
INSERT INTO table (values, to, fill)
SELECT random(), random(), random() from generate_series(1,10000);
在您的情况下,这将是:
In your case, this will be:
INSERT INTO operation (
phone_number,
age,
gender,
isActive,
date_of_surgery
) SELECT
'some-phone-' || round(random()*1000), -- for text
round(random()*70), -- for integer
(ARRAY['f','m'])[round(random())+1], -- for char/enum
(ARRAY[false,true])[round(random())+1], -- for boolean
now() + round(random()*1000) * '1 second'::interval -- for timestamps
FROM generate_series(1,10000);
更多解释。
-
generate_series 将为您提供循环,也可以访问
生成的值。
generate_series will provide you the loop, also you can access the values it generates. Those are not needed now.
文本 || round(random()* 1000)
可以生成类似 text-1212的唯一
字符串。
'text' || round(random()*1000)
can generate 'text-1212'-like unique
strings.
round(random()* 70)
-您需要四舍五入,因为random()返回的
浮点值介于0和1之间。
round(random()*70)
- you need to round, because random() returns a
floting point value between 0 and 1.
(ARRAY ['f','m'])[round(random())+ 1]
-枚举一样,建立一个
数组并为其生成一个随机索引
(ARRAY['f','m'])[round(random())+1]
- for enum and alike, build an
array and generate a random index for it
now()+ round(random() * 1000)*'1秒':: interval
-获取基线
日期并添加随机时间时间间隔。
(小提琴)
这篇关于PostgreSQL循环随机插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!