MySQL 隨機獲取資料的方法,支援大資料量

2022-06-16 22:09:11 字數 2051 閱讀 1902

在mysql中帶了隨機取資料的函式,在mysql中我們會有rand()函式,很多朋友都會直接使用,如果幾百條資料肯定沒事,如果幾萬或百萬時你會發現,直接使用是錯誤的。下面我來介紹隨機取資料一些優化方法。

select * from table_name order by rand() limit 5;

rand在手冊裡是這麼說的:

rand()

rand(n)

返回在範圍0到1.0內的隨機浮點值。如果乙個整數引數n被指定,它被用作種子值。

mysql> select

rand();

-> 0.5925

mysql> select rand(20

); -> 0.1811

mysql> select rand(20

); -> 0.1811

mysql> select

rand();

-> 0.2079

mysql> select

rand();

-> 0.7888

你不能在乙個order by子句用rand()值使用列,因為order by將重複計算列多次。

然而在mysql3.23中,你可以做: select * from table_name order by rand(),

這是有利於得到乙個來自select * from table1,table2 where a=b and c注意在乙個where子句裡的乙個rand()將在每次where被執行時重新評估。

網上基本上都是查詢max(id) * rand()來隨機獲取資料。

select *from `table` as t1 join (select round(rand() *(select max(id) from `table`)) as id) as t2

where t1.id >=t2.id

order by t1.id asc limit

5;

但是這樣會產生連續的5條記錄。解決辦法只能是每次查詢一條,查詢5次。即便如此也值得,因為15萬條的表,查詢只需要0.01秒不到。

上面的語句採用的是join,mysql的論壇上有人使用

select *from `table`

where id >= (select floor( max(id) *rand()) from `table` )

order by id limit

1;

我測試了一下,需要0.5秒,速度也不錯,但是跟上面的語句還是有很大差距

後來請教了baidu,得到如下**

完整查詢語句是:

select *from `table`

where id >= (select floor( rand() * ((select max(id) from `table`)-(select min(id) from `table`)) +(select min(id) from `table`)))

order by id limit

1;

select *from `table` as t1 join (select round(rand() * ((select max(id) from `table`)-(select min(id) from `table`))+(select min(id) from `table`)) as id) as t2

where t1.id >=t2.id

order by t1.id limit

1;

最後在php中對這兩個語句進行分別查詢10次,

前者花費時間 0.147433 秒

後者花費時間 0.015130 秒

執行效率需要0.02 sec.可惜的是,只有mysql 4.1.*以上才支援這樣的子查詢.

注意事項 檢視官方手冊,也說rand()放在order by 子句中會被執行多次,自然效率及很低。

以上的sql語句最後一條,本人實際測試通過,100w資料,瞬間出結果。

mysql獲取隨機資料的方法

1.order by rand 資料多了極慢,隨機性非常好,適合非常小資料量的情況。複製 如下 select from table name as r1 join select round rand www.cppcns.com select abs max id min id limit from...

mysql實現隨機獲取幾條資料的方法

sql語句有幾種寫法 1 select from tablename order by rand limit 想要獲取的資料條數 2 select from table where id select floor max id rand from table order by id limit 想要...

MySQL隨機獲取資料的方法,支援大資料量

select from table name order by rand limit 5 複製 rand在手冊裡是這麼說的 rand rand n 返回在範圍0到1.0內的隨機浮點值。如果乙個整數引數n被指定,它被用作種子值。mysql selectrand 0.5925 mysql selectr...