1. 程式人生 > >mysql實現隨機獲取幾條資料的方法

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 想要獲取的資料條數;

3: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 想要獲取的資料條數;

4:SELECT * FROM `table`WHERE id >= (SELECT floor(RAND() * (SELECT MAX(id) FROM `table`))) ORDER BY id LIMIT 想要獲取的資料條數;

5: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 想要獲取的資料條數;

6: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的查詢時間>>2的查詢時間>>5的查詢時間>6的查詢時間>4的查詢時間>3的查詢時間,也就是3的效率最高。