1]普通方法, 效率太低
代码如下 复制代码
select * from table order by rand() limit 10;
[2] join的方法:
代码如下 复制代码
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 10;
再把语句完善一下,加上min(id)的判断。我在最开始测试的时候,就是因为没有加上min(id)的判断,结果有一半的时间总是查询到表中的前面几行。
完整查询语句是:
代码如下 复制代码
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 1;
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 1;
前者花费时间 0.147433 秒
后者花费时间 0.015130 秒
都是查询10咨物。
