For a fast approach try this:
SELECT *
FROM (
SELECT @cnt := COUNT(*) + 1,
@lim := 10
FROM t_random
) vars
STRAIGHT_JOIN
(
SELECT r.*,
@lim := @lim - 1
FROM t_random r
WHERE (@cnt := @cnt - 1)
AND RAND(20090301) < @lim / @cnt
) i
See this article for a detailed description of how it works:
A simpler (but slow way) is to use ORDER BY RAND()
:
SELECT *
FROM yourtable
ORDER BY RAND()
LIMIT 6
From the manual:
... you can retrieve rows in random order like this:
mysql> SELECT * FROM tbl_name ORDER BY RAND();
ORDER BY RAND() combined with LIMIT is useful for selecting a random sample from a set of rows:
mysql> SELECT * FROM table1, table2 WHERE a=b AND c<d
-> ORDER BY RAND() LIMIT 1000;
RAND() is not meant to be a perfect random generator. It is a fast way to generate random numbers on demand that is portable between platforms for the same MySQL version.
If you have a unique id
field which is incrementing from 1 to n without any gaps you can improve performance even more by choosing six random numbers in [1, n] and fetching the six rows with those ids. This avoids scanning the full table.