0

我有categories带有列category_id和的表name。我想products用随机数据生成新表。表products有列product_id, category_id, name, price。我想给每个产品随机category_id

我的表格生成脚本products

INSERT INTO products (category_id, name, price) 
SELECT
   (SELECT category_id FROM categories OFFSET floor(random()*50) LIMIT 1),
   ('Product ' || i),
   round(cast(random() * 999 + 1 as numeric), 2)
FROM generate_series(1,100) as seq(i)

此脚本生成 100 行产品,但每个产品都有相同的category_id. 我做错了什么?

4

1 回答 1

1

“问题”是 Postgres 在优化方面过于激进。它能够识别出子查询只能被调用一次——以某种方式忽略了random()不是确定性函数的事实。

解决此问题的一种方法涉及相关子查询:

SELECT (SELECT category_id
        FROM categories c
        WHERE c.category_id <> seq.i
        OFFSET floor(random()*3)
        LIMIT 1
       ),
       ('Product ' || i),
       round(cast(random() * 999 + 1 as numeric), 2)
FROM generate_series(1,100) as seq(i);
于 2017-04-15T11:12:29.217 回答