How to SELECT random rows from table with an exact number of row?

一个人想着一个人 提交于 2019-12-18 09:42:03

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!