There are many ways to implement random sorting in MySQL:
1. Use the RAND() function
By using the RAND() function, you can generate a random number for each record and then sort it by this random number. For example:
SELECT * FROM table_name ORDER BY RAND();
This method is simple and easy to use, but is not suitable for tables with large data volumes, because it requires generating a random number for each record and sorting it.
2. Use the UUID() function
The UUID() function can generate a globally unique identifier. Random sorting can be achieved by taking the results of the UUID() function as a sorting field. For example:
SELECT * FROM table_name ORDER BY UUID();
This method is not affected by the amount of data, but the sorting result is not really random, but is sorted according to the unique identifier generated by the UUID.
3. Use the hash value of the sort field
If there is a unique sort field, you can use the hash function to convert it into a random number and sort it. For example:
SELECT * FROM table_name ORDER BY MD5(sort_column);
This method is suitable for cases where there are unique sort fields, but the sort results may have some duplication.
4. Use custom functions
By customizing a function, use a random number generation algorithm in the function and use it as a sorting field. For example:
CREATE FUNCTION random_sort() RETURNS FLOAT BEGIN DECLARE rand_num FLOAT; SET rand_num = RAND(); RETURN rand_num; END;
SELECT * FROM table_name ORDER BY random_sort();
This method can implement random sorting based on a custom random number generation algorithm, but attention should be paid to the execution efficiency and randomness of the function.
Note: The above method is only applicable to ordinary queries. If you need to maintain the random order of data in multiple queries, you need to provide a fixed random seed during the query and use the same random seed in subsequent queries.
This is the end of this article about the implementation of several methods of random sorting in MySQL. For more related content on random sorting of MySQL, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!