问题
Using PHP and MySQL, I want to select only 6 rows from table which has more rows everyday. I try to use the code like:
SELECT * FROM table WHERE rand()<=$fragment LIMIT 6
where fragment is 6 divided by number of total rows. The number of rows in result mostly be 6, but sometime less than 6.
How to get the result that have exactly six rows?
回答1:
SELECT * FROM table
WHERE some condition
ORDER BY RAND()
LIMIT 6
回答2:
SELECT * FROM table order by rand() limit 6;
That will always give you exactly 6 rows selected randomly (as long as there are at least 6 rows in your table).
来源:https://stackoverflow.com/questions/9961210/how-to-select-random-rows-from-table-with-an-exact-number-of-row