首页 > 解决方案 > PostgreSQL Generate_Series() 插入未完成

问题描述

所以我试图跳过使用外部脚本生成模拟数据,而是在 PostgreSQL 中使用 generate_series() 。如果我确实尝试更少的行,那么它最多会返回“无法写入块:临时日志文件......设备上没有足够的空间”。

代码:

CREATE TABLE posts(
    id INTEGER PRIMARY KEY,
    author VARCHAR(20),
    likes INTEGER,
    content VARCHAR(200),
    posted TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

INSERT INTO posts
SELECT DISTINCT id, author, likes, content, posted FROM 
    generate_series(1,10000) AS id, substr(md5(random()::text), 0, 20) AS 
    author, generate_series(1,10000) AS likes, md5(random()::text) AS 
    content, generate_series('2007-02-01'::timestamp, 
    '2018-04-01'::timestamp, '1 hour') AS posted;

我能想到的几种可能性:

标签: postgresqlgenerate-series

解决方案


通过执行您在 from 子句中所做的操作,您将获得您生成的所有集合的笛卡尔积。如果您只想生成 10000 行,则如下所示是您想要的。

INSERT INTO posts
SELECT id, substr(md5(random()::text), 0, 20) AS author, (random() * 100)::integer AS likes, 
    md5(random()::text) AS content, '2007-02-01'::timestamp + (id * '1 hour'::interval) AS posted 
FROM 
    generate_series(1,10000) AS id

推荐阅读