mysql高效率随机获取n条数据写法

今天做项目遇到这个问题,本来想用mysql自带的随机函数来实现,但是想到这样做功能是实现了,但是效率真的好差!一下子想不到好的方法,就去网上找了一下,记录下来,好好研究学习一下。

ID连续的情况下(注意不能带where,否则结果不好):

SELECT *
FROM `talbe` 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;

ID不连续的情况下:

SELECT * FROM `table` 
WHERE id >= (SELECT floor(RAND() * (SELECT MAX(id) FROM `table`)))  and a = "a" and b = b
ORDER BY id LIMIT 4;

假设你的表叫做mm_account,并且有一个字段叫id。最快的方法如下(随机获取5条):

SELECT * FROM talbe WHERE id >= ((SELECT MAX(id) FROM table)-(SELECT MIN(id) FROM table)) * RAND() + (SELECT MIN(id) FROM table) limit 5;

如果带where语句,上面就不适合了。带where语句请看下面:

SELECT *
FROM `table` AS t1 JOIN (SELECT ROUND(RAND() * (
(SELECT MAX(id) FROM `table` where id < 1000 )-(SELECT MIN(id) FROM `table` where id < 1000 ))+(SELECT MIN(id) FROM `table` where id < 1000 )) AS id) AS t2
WHERE t1.id >= t2.id
ORDER BY t1.id LIMIT 5;
posted @ 2018-11-02 15:08  第一夫人  阅读(3928)  评论(1编辑  收藏  举报