ORDER BY RAND() is not the only solution?
Although ORDER BY RAND()
is a common way to randomize results in MySQL, it is inefficient when multiple random results are needed. Because this requires sorting the entire result set, it is extremely inefficient for large tables.
More efficient alternatives
In order to optimize such queries, it is recommended to use a more efficient method:
<code class="language-sql">SELECT g.* FROM table g JOIN (SELECT id FROM table WHERE RAND() < p><strong>工作原理</strong></p><p>此优化后的查询使用了以下技术:</p></code>
Advantages of optimization methods
This optimization method has the following advantages:
ORDER BY RAND()
, especially for large result sets. Limitations
It is important to note that this method may not work in all situations. Complex queries involving multiple joins or WHERE
clauses may require more complex subqueries and optimization techniques.
The above is the detailed content of Is ORDER BY RAND() the Best Way to Get Multiple Random Results in MySQL?. For more information, please follow other related articles on the PHP Chinese website!