Home > Database > Mysql Tutorial > body text

How to Randomly Select and Sort Data in MySQL?

Mary-Kate Olsen
Release: 2024-11-01 01:57:28
Original
959 people have browsed it

 How to Randomly Select and Sort Data in MySQL?

Randomizing and Sorting MySQL Data

In MySQL, you can combine the ORDER BY clause with the rand() function to retrieve random records from a table. However, if you attempt to further sort the randomized results using another column, you may encounter unexpected behavior.

To address this, the query should be structured as a subquery. The inner query retrieves 20 random users using ORDER BY rand() LIMIT 20.

<br>SELECT * FROM users ORDER BY rand() LIMIT 20<br>

The resulting temporary table, which contains the random users, is then referenced by the outer query. The outer query re-sorts the temporary table by the name column in ascending order:

<br>SELECT * FROM <br>(</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">SELECT * FROM users ORDER BY rand() LIMIT 20
Copy after login

) T1
ORDER BY name ASC

This approach ensures that the final result set consists of 20 randomly selected users, ordered by their names in ascending order.

The above is the detailed content of How to Randomly Select and Sort Data in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!