php mysql怎么随机获取几条数据

php mysql随机获取几条数据的方法:1、通过“SELECT * FROM tablename ORDER BY RAND() LIMIT”获取数据;2、通过“ORDER BY t1.id ASC LIMIT”方式获取指定条数的数据等。

本文操作环境:Windows7系统、PHP7.1版、Dell G3电脑。

php 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 想要获取的数据条数;

反馈:

实测 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视频教程》

hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » php mysql怎么随机获取几条数据