Postgres 查询 return 意外结果
Postgres query return unexpected result
从 table foo.
中获取随机行
create table foo as
select generate_series(1,1000000) as val;
'val' 是串行字段(不是主要字段)。字段没有中断。
此查询可能 return 0,1,2,3,4... 行和所有行中的 val 具有不同的值。为什么?
select * from foo where val =
(floor(random() * (select max(val) from foo))+1)::int;
将查询稍微更改为
select * from foo where val =
(select (floor(random() * (select max(val) from foo))+1)::int as v);
结果符合预期,来自 table
的单个随机行
PostgreSQL 的随机函数是 volatile 这意味着它可能 return 每次评估时都有不同的值,您的第一个查询将不同的随机数与 table 的每一行进行比较,你的第二个计算一个随机值并将每一行与该值进行比较。
假设您想要一副洗好的牌:
select * from deck_of_cards order by random();
或者 yahtzee 我们更适合您:
select floor(random()*6)+1::int from generate_series (1,6);
从 table foo.
中获取随机行create table foo as
select generate_series(1,1000000) as val;
'val' 是串行字段(不是主要字段)。字段没有中断。
此查询可能 return 0,1,2,3,4... 行和所有行中的 val 具有不同的值。为什么?
select * from foo where val =
(floor(random() * (select max(val) from foo))+1)::int;
将查询稍微更改为
select * from foo where val =
(select (floor(random() * (select max(val) from foo))+1)::int as v);
结果符合预期,来自 table
的单个随机行PostgreSQL 的随机函数是 volatile 这意味着它可能 return 每次评估时都有不同的值,您的第一个查询将不同的随机数与 table 的每一行进行比较,你的第二个计算一个随机值并将每一行与该值进行比较。
假设您想要一副洗好的牌:
select * from deck_of_cards order by random();
或者 yahtzee 我们更适合您:
select floor(random()*6)+1::int from generate_series (1,6);