ORDERBYRAND () optimization of mysql _ MySQL

Source: Internet
Author: User
Mysql's ORDERBYRAND () optimization bitsCN.com

Mysql order by rand () optimization

We all know that the use of order by rand () in mysql is very slow when there is a large amount of data, because it will cause mysql to scan the entire table, so it will not use the index,

So order by rand () is already in the restricted area when it is used for random, so we should try to avoid using order by rand, therefore, it must be replaced or optimized by other methods.

When we have a random piece of data, consider the following:

[Php] $ DBI = new dbi2 ($ __dbserver); $ num = $ DBI-> result ('SELECT count (1) as num from article '); // obtain the total number of entries. use the database engine MyISAM $ num = $ num [0] ['num']-1; $ num = rand (1, $ num ); $ list = $ DBI-> result ('Select id FROM acticle order by viewcount desc limit ?, 1', $ num); // use limit

To avoid full table scan, a small portion of the data can be retrieved at random, which falls into a small range:

[Php] $ DBI = new dbi2 ($ __dbserver ); // Obtain 10 random strings in the range of 200. $ list = $ DBI-> result ('select id FROM (SELECT id FROM acticle order by viewcount desc limit ?) X order by rand () LIMIT? ', 200,10 );

BitsCN.com

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.