Possible Duplicate:
Selecting Random Rows in MySQL
I'm creating a simple web application using PHP and MySQL. In it, I need to randomly select a small set of rows from a table in a random order. How can I achieve such thing using MySQL?
To get a single row randomly, we can use the LIMIT Clause and set to only one row. ORDER BY clause in the query is used to order the row(s) randomly. It is exactly the same as MYSQL. Just replace RAND( ) with RANDOM( ).
mysql> SELECT DISTINCT last_name, first_name -> FROM person_tbl -> ORDER BY last_name; An alternative to the DISTINCT command is to add a GROUP BY clause that names the columns you are selecting. This has the effect of removing duplicates and selecting only the unique combinations of values in the specified columns.
CREATE TEMPORARY TABLE tmptable SELECT * FROM myTable; UPDATE tmptable SET primaryKey = 0; INSERT INTO myTable SELECT * FROM tmptable; This is of course to duplicate all the rows in the table.
SELECT * FROM table ORDER BY RAND() LIMIT 10;
Edit:
Useful information about the MySQL RAND() function can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With