一直以為mysql隨機查詢幾條數據,就用
SELECT * FROM `table` ORDER BY RAND() LIMIT 5
就可以了。
但是真正測試一下才發現這樣效率非常低。一個15萬余條的庫,查詢5條數據,居然要8秒以上
查看官方手冊,也說rand()放在ORDER BY 子句中會被執行多次,自然效率及很低。
You cannot use a column with RAND() values in an ORDER BY clause, because ORDER BY would evaluate the column multiple times.
搜索Google,網上基本上都是查詢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;
上面的語句采用的是JOIN,mysql的論壇上有人使用
SELECT *
FROM `table`
WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table` )
ORDER BY id LIMIT 1;
我測試了一下,需要0.5秒,速度也不錯,但是跟上面的語句還是有很大差距。總覺有什麼地方不正常。
於是我把語句改寫了一下。
SELECT * FROM `table`
WHERE id >= (SELECT floor(RAND() * (SELECT MAX(id) FROM `table`)))
ORDER BY id LIMIT 1;
這下,效率又提高了,查詢時間只有0.01秒
最後,再把語句完善一下,加上MIN(id)的判斷。我在最開始測試的時候,就是因為沒有加上MIN(id)的判斷,結果有一半的時間總是查詢到表中的前面幾行。
完整查詢語句:
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; --by www.jbxue.com
最後在php中對這兩個語句進行分別查詢10次,
前者花費時間 0.147433 秒
後者花費時間 0.015130 秒
看來采用JOIN的語法比直接在WHERE中使用函數效率還要高很多。