MySQL查询随机数据的4种方法和性能对比_MySQL
下面从以下四种方案分析各自的优缺点。
方案一:
SELECT * FROM `table` ORDER BY RAND() LIMIT 0,1;
这种方法的问题就是非常慢。原因是因为MySQL会创建一张零时表来保存所有的结果集,然后给每个结果一个随机索引,然后再排序并返回。
有几个方法可以让它快起来。
基本思想就是先获取一个随机数,然后使用这个随机数来获取指定的行。
由于所有的行都有一个唯一的id,我们将只取最小和最大id之间的随机数,然后获取id为这个数行。为了让这个方法当id不连续时也能有效,我们在最终的查询里使用”>=”代替”=”。
为了获取整张表的最小和最大id,我们使用MAX()和MIN()两个聚合函数。这两个方法会返回指定组里的最大和最小值。在这里这个组就是我们表里的所有id字段值。
方案二:
$range_result = mysql_query( " SELECT MAX(`id`) AS max_id , MIN(`id`) AS min_id FROM `table` ");
$range_row = mysql_fetch_object( $range_result );
$random = mt_rand( $range_row->min_id , $range_row->max_id );
$result = mysql_query( " SELECT * FROM `table` WHERE `id` >= $random LIMIT 0,1 ");
就像我们刚才提到的,这个方法会用唯一的id值限制表的每一行。那么,如果不是这样情况怎么办?
下面这个方案是使用了MySQL的LIMIT子句。LIMIT接收两个参数值。第一个参数指定了返回结果第一行的偏移量,第二个参数指定了返回结果的最大行数。偏移量指定第一行是0而不是1。
为了计算第一行的偏移量,我们使用MySQL的RAND()方法从0到1之间生成一个随机数。然后我们把这个数字跟我们用COUNT()方法获取倒的表记录数相乘。由于LIMIT的参数必须是int型而不能是float,我们使用FLOOR()来处理结果。FLOOR()会计算小于表达式的最大值。最终的代码就是这样:
方案三:
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `table` ");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( " SELECT * FROM `table` LIMIT $offset, 1 " );
在MySQL 4.1以后我们可以使用子子查询合并上面两个方法:
方案四:
SELECT * FROM `table` WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table` ) ORDER BY id LIMIT 1;
这个方案跟方案二有同样的弱点,只对有唯一id值的表有效。
记住我们最初寻找选择随机行的替代方法的原因,速度!所以,这些方案的在执行时间上的比较会怎么样?我不会指出硬件和软件配置或者给出具体的数字。大概的结果是这样的:
最慢的是解决方案一(我们假定它用了100%的时间)。
方案二用了79%
方案三

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In today's information age, personal computers play an important role as an indispensable tool in our daily lives. As one of the core software of computers, the operating system affects our usage experience and work efficiency. In the market, Microsoft's Windows operating system has always occupied a dominant position, and now people face the choice between the latest Windows 11 and the old Windows 10. For ordinary consumers, when choosing an operating system, they do not just look at the version number, but also understand its advantages and disadvantages.

Templating: Pros and Cons Templating is a powerful programming technique that allows you to create reusable blocks of code. It offers a range of advantages, but also some disadvantages. Pros: Code Reusability: Templating allows you to create common code that can be reused throughout your application, reducing duplication and maintenance efforts. Consistency: Templating ensures that code snippets are implemented the same way in different locations, improving code consistency and readability. Maintainability: Changes to a template are reflected simultaneously in all code that uses it, simplifying maintenance and updates. Efficiency: Templating saves time and effort because you don't have to write the same code over and over again. Flexibility: Templating allows you to create configurable blocks of code that can be easily adapted to different application needs. shortcoming

JavaServlet is a Java class used to build dynamic web pages and serves as a bridge between client and server. Working principle: receive requests, initialize Servlet, process requests, generate responses and close Servlet. Pros: Portable, scalable, secure and easy to use. Disadvantages: Overhead, coupling, and state management. Practical case: Create a simple Servlet to display the "Hello, Servlet!" message.

The choice of PHP framework depends on project needs and developer skills: Laravel: rich in features and active community, but has a steep learning curve and high performance overhead. CodeIgniter: lightweight and easy to extend, but has limited functionality and less documentation. Symfony: Modular, strong community, but complex, performance issues. ZendFramework: enterprise-grade, stable and reliable, but bulky and expensive to license. Slim: micro-framework, fast, but with limited functionality and a steep learning curve.

Advantages and Disadvantages of Using Chinese to Name Java Variables In Java programming, we usually use English to name identifiers such as variables, methods, and classes. However, sometimes we can also consider using Chinese as part of the identifier. This article will explore the advantages and disadvantages of using Chinese named Java variables and give some specific code examples. Advantage 1: Improve code readability. Using Chinese named Java variables can make the code easier to understand and read. After all, our brains understand and recognize Chinese more naturally and fluently than English. For non-English

With the development of Golang, more and more compilers have been developed. When choosing a compiler, developers need to consider many factors, such as reliability, performance, ease of use, etc. This article will summarize some common Golang compilers and explore their advantages and disadvantages to help developers better choose the compiler that suits them. Go official compiler Go official compiler is Golang's default compiler and a widely recognized compiler in the Golang community. It has the following advantages: good stability, small size and compilation

C language and Python: analysis of applicable scenarios and advantages and disadvantages In the field of computer programming, C language and Python are two very popular programming languages. They each have unique advantages and disadvantages and are suitable for different scenarios. This article will conduct an in-depth analysis of C language and Python, discussing their applicable scenarios, advantages and disadvantages. 1. C language applicable scenarios: C language is a process-oriented programming language with high efficiency and excellent performance. It is suitable for the development of system software, drivers and embedded systems that require a high degree of control and efficiency.

Java Framework Pros and Cons: Pros: Accelerated development Improved code quality Rich ecosystem Code reuse Cons: Performance overhead Complexity and learning curve Lack of flexibility Maintenance burden
