他們原來都想用PHP的實現隨機,但取出多條好像要進行兩次以上查詢.
翻了手冊,找到了下面這個語句,可以完成任務了,但效率較低
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<d ORDER BY RAND() LIMIT 1000的集合的隨機樣本。注意在一個WHERE子句裡的一個RAND()將在每次WHERE被執行時重新評估。
但我試了一下,8千條記錄的表,執行一次需要0.08 sec,.慢了些
後來請教了google,得到如下代碼
SELECT * FROM table_name AS r1 JOIN (SELECT ROUND(RAND() * (SELECT MAX(id) FROM table_name)) AS id) AS r2 WHERE r1.id >= r2.id ORDER BY r1.id ASC LIMIT 5;
執行效率需要0.02 sec.可惜的是,只有mysql 4.1.*以上才支持這樣的子查詢.
下面是其它網友的補充:
select id from zhyx_items order by rand() 這樣效率太低了
優化sql語句之後:
SELECT t1.id FROM zhyx_items AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM zhyx_items)-(SELECT MIN(id) FROM zhyx_items))+ (SELECT MIN(id) FROM zhyx_items)) AS id) AS t2 WHERE t1.id >= t2.id ORDER BY t1.id LIMIT 0,5;