萬盛學電腦網

 萬盛學電腦網 >> 數據庫 >> mysql教程 >> mysql隨機查詢的優化

mysql隨機查詢的優化

  mysql隨機查詢最常見的寫法如下:

  1 SELECT * FROM tablename ORDER BY RAND() LIMIT 1

  php手冊上如此解釋:

  About selecting random rows from a MySQL table:

  SELECT * FROM tablename ORDER BY RAND() LIMIT 1

  works for small tables, but once the tables grow larger than 300,000 records or so this will be very slow because MySQL will have to process ALL the entries from the table, order them randomly and then return the first row of the ordered result, and this sorting takes long time. Instead you can do it like this (atleast if you have an auto_increment PK):

  SELECT MIN(id), MAX(id) FROM tablename;

  Fetch the result into $a

  $id=rand($a[0],$a[1]);

  SELECT * FROM tablename WHERE id>=’$id’ LIMIT 1.

  大意是說,如果你用 ORDER BY RAND() 來隨機讀取記錄的話,當數據表記錄達到30萬或者更多的時候,mysql將非常吃力.所以php手冊裡給了一種方法,結合php來實現:

  首先 SELECT MIN(id), MAX(id) FROM tablename; 取數據庫裡最大最小值;

  然後 $id=rand($a[0],$a[1]); 產生一個隨機數;

  最後 SELECT * FROM tablename WHERE id>=’$id’ LIMIT 1 將上面產生的隨機數帶入查詢;

  很顯然上面是最有效率的。

  如果需要多條記錄的話,就循環查詢,並記得去除重復記錄。

  其它的一些方法可以自行查閱一下google或者百度。

copyright © 萬盛學電腦網 all rights reserved