小丁的屋舍
PHP | Mysql怎么随机获取几条数据
2022-08-04
查看标签
345次浏览

在制作个人主页的时候,发现项目过多,但不方便全部展示,这时候就需要随机抽取几个项目来作为展示当然想要最新项目的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 想要获取的数据条数;

实测结果

38万数据,随机取10条 1 可以随机取值,执行时间1-2秒。 2 运行超过20秒没反应,试了3次。 3 取的10条数据是连续的ID,执行0.001秒。 4 随机取10条,id在1-4000之间,执行0.003秒,试了10次以上。 5 随机取10条,id在1-4000之间,执行0.003秒,试了10次以上。 6 取的10条数据是连续的ID,执行0.001秒。

来源:PHP中文网