How to SELECT random rows from table with an exact

2019-01-29 10:27发布

问题:

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).