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() 來隨機讀取記錄的話,當數(shù)據(jù)表記錄達到30萬或者更多的時候,mysql將非常吃力.所以php手冊里給了一種方法,結(jié)合php來實現(xiàn):
首先 SELECT MIN(id), MAX(id) FROM tablename; 取數(shù)據(jù)庫里最大最小值;
然后 $id=rand($a[0],$a[1]); 產(chǎn)生一個隨機數(shù);
最后 SELECT * FROM tablename WHERE id>=’$id’ LIMIT 1 將上面產(chǎn)生的隨機數(shù)帶入查詢;
很顯然上面是最有效率的。
如果需要多條記錄的話,就循環(huán)查詢,并記得去除重復記錄。
其它的一些方法可以自行查閱一下google或者百度。
新聞熱點
疑難解答
圖片精選