Oralce 随机取一条数据

Oralce随机数

select * from (select * from fbb_bagitem order by dbms_random.value) where rownum=1

首先第一个是随机抽取6个

    select * from  (select * from tablename order by dbms_random.value) where  rownum<7


    这个方法的原理我认为应该是把表中的数据全部查询出来按照随机数进行排列后在从查询出来的数据中查询中6条记录,这个方法我在使用的过程中发现,如果记录一多的话查询的速度有一点点的慢

第二个是利用oracle的sample()或sample block方法
选择10%的记录
select * from t1 sample(10)
选择0.1%的记录
select * from t1 sample(0.1)

根据数据块选择1%的记录
select * from t1 sample block(1)

使用数据块选择与使用记录行选择的区别:使用数据块选择表示样本的采集是基于数据块采集的,也就是说样本如果一个数据块被采集为样本,则数据块里的记录全部都是样本


样本统计是基于统计学采集的,是有概率问题,不一定完全准确,如你要取50%的记录,但实际可能返回给你49%的记录集,也可能返回给你51%的记录集


例如

如果表T1有数据块B1,B2
B1有记录R1,R2,R3,R4,R5
B2有记录R6,R7,R8,R9,R10

如果使用如下SQL选择50%的数据
select * from t1 sample block(50)

则返回的结果可能是数据块B1的记录
R1,R2,R3,R4,R5
也可能是数据块B2的记录
R6,R7,R8,R9,R10
也可能不返回记录集


如果使用如下SQL选择50%的数据
select * from t1 sample (50)

则返回的结果可能是
R2,R3,R5,R8,R9
也可能是如下的样子
R1,R3,R4,R8




应用示例:
随机从表中取中1条记录,选取记录的概率是1%
select * from t1 sample(1) where rownum=1

随机从表中取中10条记录,选取记录的概率是0.1%
select * from t1 sample(0.1) where rownum<=10

注:当选取的概率越低,访问表的记录数将越多


ORACLE参考手册中的相关说明:

sample_clause
The sample_clause lets you instruct Oracle to select from a random sample of rows from the table, rather than from the entire table.


BLOCK
BLOCK instructs Oracle to perform random block sampling instead of random row sampling.


sample_percent
sample_percent is a number specifying the percentage of the total row or block count to be included in the sample. The value must be in the range .000001 to (but not including) 100.

Restrictions on Sampling During Queries
You can specify SAMPLE only in a query that selects from a single table. Joins are not supported. However, you can achieve the same results by using a CREATE TABLE ... AS SELECT query to materialize a sample of an underlying table and then rewrite the original query to refer to the newly created table sample. If you wish, you can write additional queries to materialize samples for other tables.

When you specify SAMPLE, Oracle automatically uses cost-based optimization. Rule-based optimization is not supported with this clause.

--------------------------------------------------------------------------------
Caution:
The use of statistically incorrect assumptions when using this feature can lead to incorrect or undesirable results.

--------------------------------------------------------------------------------

译:
Sample选项
使用sample选项的意思是指定Oracle从表中随机选择记录样本,这样比从整个表中选择更高效.

block选项
加上 BLOCK选项时表示随机取数据块,而不是随机取记录行.

sample_percent选项
sample_percent是指定总记录行或数据块为数据样本的百分比数值,这个值只能在0.000001到100之间,且不能等于100

限制
只能在单表查询的SQL中指定sample选项,不支持有连接的查询。但是,你可以使用CREATE TABLE ... AS SELECT查询的语法完成同样的效果,然后再采用新建的样本表重新编写查询SQL。

当你指定用sample时,不支持基于规则(rule)的优化法则,ORACLE自动使用基本成本(cost)的优化法则

猜你喜欢

转载自takeme.iteye.com/blog/1931834