Postgresql 从表中获取随机数据会导致奇怪的结果
下面的查询应该提供一行,而不是两行。与博士后合作11.3。 这个怎么了?with select将索引从10到120标准化。主选择仅限于10到120之间的随机整数,并与xx列匹配。 我不明白博士后回来的结果Postgresql 从表中获取随机数据会导致奇怪的结果,postgresql,Postgresql,下面的查询应该提供一行,而不是两行。与博士后合作11.3。 这个怎么了?with select将索引从10到120标准化。主选择仅限于10到120之间的随机整数,并与xx列匹配。 我不明白博士后回来的结果 postgres# select row_number() over(order by matid) * 10 as xx, matid from materials; xx | matid -----+------- 10 | 10 20 | 20 30 |
postgres# select row_number() over(order by matid) * 10 as xx, matid from materials;
xx | matid
-----+-------
10 | 10
20 | 20
30 | 30
40 | 40
50 | 50
60 | 60
70 | 70
80 | 110
90 | 120
100 | 130
110 | 140
120 | 150
(12 rows)
postgres@=# with am as (select row_number() over(order by matid) * 10 as xx, matid from materials) select am.matid from am where xx::integer = (round((random()*110)/10)*10+10)::integer;
matid
-------
60
120
(2 rows)
您的查询可能返回0行、1行或多行。
WHERE
子句:
where xx::integer = (round((random()*110)/10)*10+10)::integer
对CTE的每一行反复执行,每次产生一个新的随机数。因此,最终的结果集是不可预测的,因为表达式
(round((random()*110)/10)*10+10)::integer
返回的值在整个查询执行过程中不是常量。看 如果要将一个常量随机数与CTE的所有行进行比较,请在另一个CTE中定义它,如下所示:
with
am as (
select row_number() over(order by matid) * 10 as xx,
matid
from materials
),
rnd as (select (round((random()*110)/10)*10+10)::integer n)
select am.matid
from am
where xx::integer = (select n from rnd);
如果问题已解决,请参阅。
@spec2019,不要忘记单击复选标记接受答案。