You can use ORDER BY RAND()
like others have suggested, but then you should also take a moment to wave goodbye to any semblance of efficiency and performance that your query may once have had. This is because you're now ordering your result set based on something that is:
- Not indexed.
- Dynamically generated.
MySQL [and pretty much any other RDBMS] is most decidedly unsuited for nearly any operation that requires introducing randomness.
Better options:
If your anticipated result set is sufficiently small to not cause:
- Delays based on the bandwidth required between your web and database server.
- Excessive memory use storing the result set.
Then simply get all of the potential content items and use array_rand()
or shuffle()
to get your random selection.
If your anticipated result set is going to be large enough that you don't want to pass the whole thing to PHP then I suggest something like:
$sql =
"SELECT COUNT(*) 'count'
FROM content_table
WHERE [your conditions]";
$rs = $dbh->query($query);
$random = rand(0,$rs['count']);
$sql =
"SELECT field1, field2, ...
FROM content_table
WHERE [your conditions]
LIMIT $random, 1";
$rs = $dbh->query($sql);
Both of which will respect your indexes.