Select Random Rows or Records in MySQL
With PHP and MySQL, you may fulfill the same task by selecting all the rows into an array and choosing a random index with php function array_rand or mt_rand (better) but that would be all big overhead to do as you have to first read in the entire table.
The correct way is to get a random row directly with MySQL is:
SELECT * FROM sometable ORDER BY RAND() LIMIT 1
That’s just one random row. If you want more than one, you’d just going to change the LIMIT clause:
SELECT * FROM sometable ORDER BY RAND() LIMIT 4
Now it will pump out 4 independent random rows.
To know the random selecting SQL query in PostgreSQL, Microsoft SQL Server, IBM DB2 or Oracle, Pete is the guy you’d be asking.
0 comments:
Post a Comment