简体   繁体   中英

MySQL select random records with limit

I have a query for selecting random records with a limit of 6.

$query = $this->pdo->prepare("SELECT * FROM `" . $this->table . "` ORDER BY rand() LIMIT " . $limit);

If I set the limit to 6, it will sometimes only show 4 records, sometimes 5.
How can I make it always show 6?
I have more than 6 records in the database.

I looked at some questions around this here but couldn't find a clear answer.

$query = $this->pdo->prepare("SELECT * FROM `" . $this->table . "` ORDER BY rand() LIMIT $limit " );

Try with : SELECT RAND(6)

$query = $this->pdo->prepare("SELECT * FROM " . $this->table . " ORDER BY RAND(6) LIMIT " . $limit);

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