oracle随机抽样

           需求是这样的:程序每隔几个小时,从表中取100个数据,监测其正确性。

           按照正常的写法,每次取出的结果都是一样的。

           select * from base_part where rownum<10,因为oracle每次的执行计划都是一样的,数据扫描方法顺序都是一样的,所以返回的结果也都是一样的。

           随机取数据的方法,一般网上有两种,

           一是用随机数排序。这种方法能够取到正确的结果,但是属于数据量很大的情况,排序是非常耗时的。而我的表基本上都在百万以上,所以这种方法只能pass了。按照随机数排序实际上是把随机数当做一列,然后排序。对应的语句为:

           SELECT t.*,DBMS_RANDOM.value FROM TableName1 t ORDER BY DBMS_RANDOM.value;

           再就是使用sample关键字,进行随机抽样。官网文档关于sample语句有很明确的说明。

           sample_clause The sample_clause lets you instruct the database to select from a random sample of data from the table, rather than from the entire table.BLOCK BLOCK instructs the database to attempt to perform random block sampling instead of random row sampling.(block说明数据库在读取数据时是随机快读取而不是随机行)

           Block sampling is possible only during full table scans or index fast full scans. If a more efficient execution path exists, then Oracle Database does not perform block sampling. If you want to guarantee block sampling for a particular table or index, then use the FULL or INDEX_FFS hint.(随机读取仅在全表扫描或者索引快速全扫描的时候有效)

           sample_percent For sample_percent, specify 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. This percentage indicates the probability of each row, or each cluster of rows in the case of block sampling, being selected as part of the sample. It does not mean that the database will retrieve exactly sample_percent of the rows of table.(sample子句中的百分比的意思是,这一行或者块被读取的可能性。例如100行数据的表,sample(10)返回的结果不一定是10行,极端情况下可能为0行和100行,根据概率论的基本知识,这个很容易理解)

           SEED seed_value Specify this clause to instruct the database to attempt to return the same sample from one execution to the next. The seed_value must be an integer between 0 and 4294967295. If you omit this clause, then the resulting sample will change from one execution to the next.(相同的种子值,返回的结果相同)

           我采用了这种方法,但是存在极端情况,就是返回结果不到100行,但是由于表比较大,上千万行,适当提高读取概率,基本上可以说是小概率事件。而且如果极端情况出现,也不会造成大的影响。所以就这样吧。

原文地址:https://www.cnblogs.com/lxlck/p/3520624.html