MySQL随机获取10条数据

方式一
最简单,但是效率最低

执行时间:9.845s

SELECT * FROM `table` ORDER BY RAND() LIMIT 10;

方式二
查询效率较高,但会产生连续的数据(查出来的数据在表里是连续性的)

执行时间:2.641s

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 10;

方式三
查询效率次之,不会产生连续数据(数据量少的话可能出现连续性数据)

执行时间:2.880s

SELECT * FROM `table` WHERE id >= ( SELECT floor( RAND() * ( SELECT MAX( id ) FROM `table` ) ) ) ORDER BY id LIMIT 10;

附录
RAND函数获得0到1之间的随机值

SELECT RAND() AS Random_Number;
# 输出:
# Random_Number
# 0.6332025068189973

欢迎一起来学习和指导,谢谢关注!

点赞