我试图掌握在 Postgres 中生成随机数据的方法,但发现我对LATERAL JOIN
. 基于我之前获得的一些帮助,我有一些代码试图:
-- 生成一系列数字
-- 生成与数字序列匹配的小时的时间戳
-- 为每一行生成一个大致正态分布的随机(ish)分数
-- 从数据库中的表中随机选择一个 ID。
最后一点不起作用。当我运行下面显示的脚本时,我得到一个随机值facility_id
,但每一行都有相同的随机值。我想要在每一行上分配的随机 ID,而不是在整个运行中全局分配一次。在程序性思维中,facility_id
是在循环之前分配的,我希望它在循环中分配。我认为这LATERAL JOIN
会帮助我在这里,但是
WITH facilities_count AS
(SELECT count(*) from facility)
SELECT hour_number AS id, -- Get numbers in sequence.
'2019-01-01 00:00'::timestamp + interval '1 HOUR' * hour_number AS stamp, -- Get hours in sequence
ABS(TRUNC(normal_rand(1, 0, 1) * 100)) AS score, -- Create a random score in a ~normal distribution.
random_facility.id
FROM (SELECT * FROM generate_series(1,8760,1) AS hour_number) generated_numbers
LEFT JOIN LATERAL
(SELECT id
FROM facility
OFFSET floor(random() * (select count from facilities_count))
LIMIT 1) random_facility
ON true;
我认为子查询可能会起作用,但我还facility_id
使用以下代码在所有行中获得了一个值:
WITH facilities_counter AS
(SELECT count(*) from facility)
SELECT hour_number AS id, -- Get numbers in sequence.
'2019-01-01 00:00'::timestamp + interval '1 HOUR' * hour_number AS stamp, -- Get hours in sequence
ABS(TRUNC(normal_rand(1, 0, 1) * 100)) AS score, -- Create a random score in a ~normal distribution.
(SELECT id FROM facility OFFSET floor(random() * (select count from facilities_counter)) LIMIT 1)
FROM (SELECT * FROM generate_series(1,8760,1) AS hour_number) generated_numbers;
我没有列出facility
表定义,但上面唯一重要的字段是id
,因此任何表都可以以相同的方式工作。
如果它对答案有任何影响,一旦我能找出解决这个问题的方法,我想使用facility_id
每一行上的随机数作为输入,从另一个表中选择其他东西。
谢谢你的帮助。我正在为此努力,不仅是为了获得解决方案,而且是为了尝试更好地了解各种工具的工作原理。我(显然)还没有到可以阅读上述代码并在脑海中预测它的行为方式的地步。获得这种理解是我自己解决问题的基础。换句话说,我不仅在尝试解决这个问题,而且还在努力缩小我的心理差距。
过早的优化
我正在编辑我的问题,因为我需要发布更多代码。
哈!很高兴看到我不是唯一一个被指控存在过早优化问题的人;-) 可以肯定的是,这在设计或审查会议中可能会被激怒。
我认为您所展示的id
是在表达式中使用的,这使得它的结果不确定。这就是我生活的地方,并重新学习我应该发布我的表格结构。我们的id
字段是 UUID。我试图将在表达式中使用 UUID 的东西拼凑在一起,但它不会改变行为。
where left(id::text,1) <> 'X' -- prevent premature optimization
您描述的过早优化,以及打败它的解决方法,不是我可以预测的行为。因为缝隙。我试过用left
表达式运行我的代码explain (costs off)
,我得到了这种输出:
CTE facilities_counter
-> Aggregate
-> Seq Scan on facility
InitPlan 3 (returns $2)
-> Limit
InitPlan 2 (returns $1)
-> CTE Scan on facilities_counter
-> Seq Scan on facility facility_1
Filter: ("left"((id)::text, 1) <> 'X'::text)
-> ProjectSet
-> Function Scan on generate_series hour_number```
I'm unclear from the output how I would distinguish the behavior you describe, which is still present here (?)