2009/03/12

optimize rand (for mysql select)

table name: blog_post
table rows: 7389147

1. rand()
select * from blog_post order by rand() limit 1;
1 min 26.08 sec

2. max() * rand()
select * from blog_post where postid >= (select floor(rand() * ((select max(postid) from blog_post) - (select min(postid) from blog_post)) + (select min(postid) from blog_post))) order by postid limit 1;
0.01 sec


3. join
select * from blog_post as t1 join(select round(rand() * ((select max(postid) from blog_post) - (select min(postid) from blog_post)) + (select min(postid) from blog_post)) as postid) as t2 where t1.postid >= t2.postid order by t1.postid limit 1;
0.03 sec

2 replys:

goooooood girl said...

your blog is so good......

Anonymous said...

good :)

Post a Comment