天天看點

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)的優化法則

繼續閱讀