简体   繁体   中英

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

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?

SELECT * FROM table 
WHERE some condition
ORDER BY RAND() 
LIMIT 6
SELECT * FROM table order by rand() limit 6;

这将始终为您提供随机选择的准确6行(只要表中至少有6行)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM