【发布时间】:2012-05-22 17:38:42
【问题描述】:
您好,我正在尝试从 oracle 数据库中选择随机记录。我尝试使用以下查询:
select field1
from (select field1 from table1 where field2='SAMPLE_VALUE' order by dbms_random.value)
where rownum <2;
这很好用,只是它非常缓慢且昂贵。
我们有更快的方法来实现这一点吗?
【问题讨论】:
您好,我正在尝试从 oracle 数据库中选择随机记录。我尝试使用以下查询:
select field1
from (select field1 from table1 where field2='SAMPLE_VALUE' order by dbms_random.value)
where rownum <2;
这很好用,只是它非常缓慢且昂贵。
我们有更快的方法来实现这一点吗?
【问题讨论】:
你可以试试 SAMPLE 子句:
select field1
from table1 sample (1)
where field2='SAMPLE_VALUE' and
rownum <=1
但是:
【讨论】:
field2='SAMPLE_VALUE'的记录怎么办?
如果记录有一些唯一的数字列,我会尝试将其与随机生成的值进行比较。像SELECT ... FROM ... WHERE id = RANDOM_VALUE 这样的东西。但是可能需要进行一些计算才能使这个唯一列和随机值具有相同的范围。
【讨论】:
您需要检查执行计划。
它可能正在对表执行full access,因此如果您可以在field2 上添加索引,那么优化器可能值得根据您的where clause 执行index range scan。
(field2我真的不了解,请仔细查看)
【讨论】: