-- select * from t limit count(*)*rand() 1;
mysql>
select count(*) into @C from t;
set @Y1 = floor(@C * rand());
set @Y2 = floor(@C * rand());
select * from t limit @Y1, 1; //在应用代码里面取Y1、Y2值,拼出SQL后执行
select * from t limit @Y2, 1;
再优化: C + Y2 + 1
-- select * from t limit count(*)*rand() 1;
mysql>
select count(*) into @C from t;
set @Y1 = floor(@C * rand());
set @Y2 = floor(@C * rand());
-- 比大小设置 @Y1 小于 @Y2
id1 = select * from t limit @Y1, 1;
select * from t where id > id1 limit @Y2 - @Y1, 1;
rand(): 随机下的性能
order by rand() 执行过程: 扫描行数很多有性能有问题的
order by rand()使用了内存临时表, 内存临时表排序的时候使用了 rowid 排序方法{优先队列排序算法}
随机排序方法
M=max(id), N=min(id), X = (M-N)*rand() + N
+ 取不小于 X 的第一个 ID 的行C=count(*) + Y, floor(C * rand()) , limit Y,1
limit Y,1
会扫描 Y+1 行再优化: C + Y2 + 1