The execution efficiency of MySQL random fetching data

Source: Internet
Author: User

I found a problem last night when I was writing a random joke from a "passing" application, my goal was to randomly draw a joke from the joke table (about tens of thousands of data volumes) and show that my SQL was initially as follows:

SQL code

select * from xiaohua limit 随机数,1

Where random numbers are generated by Java programs, when the random number of hours, the discovery of the execution speed is very fast, but when the random number of more than 1w, the execution speed is very slow, it seems that the road is not workable, so I also use the rand () MySQL () function to see the implementation efficiency, and found that efficiency is not good, Finally, through Google, I found that there are many people encounter this problem, the final SQL is as follows (speed exceeded), can go to the http://l.faqee.com/to see the performance of the joke speed:

SQL code

SELECT t1.id as id,title,content,class_name,class_id,hits FROM xiaohua AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM xiaohua )-(SELECT MIN(id) FROM xiaohua ))+(SELECT MIN(id) FROM xiaohua )) AS id) AS t2 WHERE t1.id >= t2.id ORDER BY t1.id LIMIT 1;

Forget about it!

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.