How to SELECT random rows from table with an exact

2019-01-29 10:26发布

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?

2条回答
可以哭但决不认输i
2楼-- · 2019-01-29 11:14
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).

查看更多
够拽才男人
3楼-- · 2019-01-29 11:23
SELECT * FROM table 
WHERE some condition
ORDER BY RAND() 
LIMIT 6
查看更多
登录 后发表回答