Oracle随机抽取N条记录

来源:互联网 发布:淘宝模特图 编辑:程序博客网 时间:2024/03/29 23:55
ORACLE SAMPLE 语法应用说明
转至:http://blog.csdn.net/yzsind/article/details/2173781

这两天发了一个贴子,寻找比较好的办法随机取出表的一条记录
地址见:http://www.oracle.com.cn/viewthread.php?tid=130433&extra=page%3D1
里面讨论了一些方法,其中版主valenwon加一个ROWNUM的字段并加索引是一种相对比较有效的方法,只是要改表结构,在测试库中可以,在生产库中就不行了,本文介绍了一下ORACLE SAMPLE语法的应用,采用SAMPLE也是一种解决方法,不过还不是很好,主要是返回的记录分布不均匀,要么是靠表前面的一些,要么是不返回记录。
下面是SAMPLE语法的使用示例:
选择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)的优化法则.
注意:
The use of statistically incorrect assumptions when using this feature can lead to incorrect or undesirable results.
这句话不太理解,估计是说采用样本采集特性可能会产生不准确的结果集。
1 0
原创粉丝点击