【发布时间】:2011-11-28 18:09:49
【问题描述】:
在我的 postgres 数据库中,我有以下关系(为了这个问题而简化了):
Objects (currently has about 250,000 records)
-------
n_id
n_store_object_id (references store.n_id, 1-to-1 relationship, some objects don't have store records)
n_media_id (references media.n_id, 1-to-1 relationship, some objects don't have media records)
Store (currently has about 100,000 records)
-----
n_id
t_name,
t_description,
n_status,
t_tag
Media
-----
n_id
t_media_path
到目前为止,一切都很好。当我需要查询数据时,我运行它(注意最后的limit 2,作为要求的一部分):
select
o.n_id,
s.t_name,
s.t_description,
me.t_media_path
from
objects o
join store s on (o.n_store_object_id = s.n_id and s.n_status > 0 and s.t_tag is not null)
join media me on o.n_media_id = me.n_id
limit
2
这工作正常,并按预期返回两个条目。执行时间约为 20 毫秒 - 很好。
现在每次查询运行时我都需要获得 2 个随机条目。我想我会添加order by random(),就像这样:
select
o.n_id,
s.t_name,
s.t_description,
me.t_media_path
from
objects o
join store s on (o.n_store_object_id = s.n_id and s.n_status > 0 and s.t_tag is not null)
join media me on o.n_media_id = me.n_id
order by
random()
limit
2
虽然这给出了正确的结果,但现在执行时间约为 2,500 毫秒(超过 2 秒)。这显然是不可接受的,因为它是为获取 Web 应用程序中的页面数据而运行的众多查询之一。
所以,问题是:我怎样才能获得随机条目,如上所述,但仍将执行时间保持在合理的时间内(即我的目的可以接受不到 100 毫秒)?
【问题讨论】:
-
Random 意味着您可能会连续多次获得相同的两行。这真的是你想要的吗?
-
@Catcall,根据
order by random()的用法——不是。 -
@StarShip3000,哦,它有我的答案! :)
-
@Michael Krelin - 黑客是的 +1
标签: sql postgresql optimization random