Home > Database > Mysql Tutorial > body text

mysql的ORDER BY RAND()优化_MySQL

WBOY
Release: 2016-06-01 13:31:28
Original
1161 people have browsed it

bitsCN.com

mysql的ORDER BY RAND()优化

 

我们都知道,mysql里用到ORDER BY RAND()在数据量比较多的时候是很慢的,因为会导致mysql全表扫描,故也不会用到索引,

所以ORDER BY RAND()用来随机时已经是到禁区里了,所以我们应该尽量避免使用ORDER BY RAND()才对,所以这个是需要用其他方法替代或者优化才行。

 

当我们随机一条数据时可以考虑一下:

 

[php] $DBI=new dbi2($__DBserver);  $num=$DBI->result('select count(1) as num from article');//获取总条数,数据库引擎为MyISAM采用吧  $num=$num[0]['num']-1;  $num=rand(1, $num);  $list=$DBI->result('SELECT id FROM acticle ORDER BY viewcount DESC LIMIT ?,1',$num);//利用limit  
Copy after login

随机多条数据时,为了避免全表扫描,可以取出一小部分在随机,这个随机性会落在一个小范围内:

[php] $DBI=new dbi2($__DBserver);  //在200条范围内取10条随机  $list=$DBI->result('SELECT id FROM (SELECT id FROM acticle ORDER BY viewcount DESC LIMIT ?)X ORDER BY RAND() LIMIT ?',200,10);  
Copy after login

 

 

bitsCN.com
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template