随机获取N条数据库记录的四个方法
分类: MySQL优化设计 | 发布: OurMySQL | 来源:mlsx.xplore.cn
标签: order, rand, 随机访问
我需要从一个数据库表中随机的获取N条数据库,最先想到的办法是两次访问数据库,第一次是获得记录条数M,然后在产生个N随机数Kj(0<=j<N),其中0<=kj<=M.然后获取键值为Kj的记录数。
但是两次查询数据库是其缺点,简单实现方法如下:
$range_result = mysql_query( ” SELECT MAX(id) AS max_id , MIN(id) AS min_id FROM tb_name “);
$range_row = mysql_fetch_object( $range_result );
$random = mt_rand( $range_row->min_id , $range_row->max_id );
$result = mysql_query( ” SELECT * FROM tb_name WHERE id >= $random LIMIT 0,1 “);
于是查阅其手册(MySQL),其中提到用order by rand() 和limit两结合来获取随机记录。另外google了一下,还发现了其他一些好的方法,特记录下来:
1) 采用官方的方式
select * from tb_name order by rand() limit N
2)采用类似偏移方式
select * from tb_name
where id >= (select floor(max(id) * rand()) from tb_name )
order by id asc limit N;
3)优化的方式
select *
from tb_name as r1 join
(select round(rand() *
(select max(id)
from tb_name)) as id2)
as r2
where r1.id >= r2.id2
order by r1.id asc
limit N;
上述方法,第一种效率最低,第三种最好。


11月 4th, 2009 at 21:02:39
第1种最明了
11月 26th, 2009 at 03:05:18
郁闷啊,我的网站因为备案问题,被空间关闭几天,居然被百度K了,哭…
11月 26th, 2009 at 16:20:54
支持 说的很有道理
12月 1st, 2009 at 15:26:23
好久没有来了~~过来看看博主可好
12月 13th, 2009 at 23:38:58
博主,文章不错。顶!
02月 25th, 2010 at 16:54:49
兄弟,感觉你网站速度快了好多啊··哈哈
03月 10th, 2010 at 19:42:03
Hello!
03月 10th, 2010 at 20:23:01
火车(www.cn-auto.org)
【祝】早晨当朝霞舞动着【福】
【祝】柔曼翅膀将你梦忆【福】
【祝】轻轻唤醒一丝清新【福】
【祝】空气一缕快乐阳光【福】,
【祝】早晨带给你好心情【福】
【祝】思念你是一种温馨【福】
【祝】思念是千万个心愿【福】
03月 11th, 2010 at 02:40:48
有点意思。。
03月 11th, 2010 at 07:44:01
Hello!
03月 12th, 2010 at 05:47:17
half life of lisinopril 58996 voltaren made 56847 phentermine paris
cheap acetylleucine pills online 24058 miltefosine sale of 41110