Answer the question
In order to leave comments, you need to log in
How to select one random MySQL record?
Hello!
There is a table, and you need to select one random record that satisfies some condition.
My own version:
1. I count the number of records for the given condition (SELECT * FROM ... WHERE ...)
2. I select a random record. SELECT * FROM `ex4` WHERE ... LIMIT '.rand(0, count ).', 1';
Are there better options? Thank you.
Answer the question
In order to leave comments, you need to log in
If you choose one, then it is quite possible:
If you need several, then this approach is not recommended because RAND () greatly reduces the performance of the query.
If PK int.
select min(id),max(id) from table where ... ; // if the data does not change often, you can cache the values
$rand = get_rand($min_id, $max_id);
select * from table where id => $rand and ... limit 1;
That's what I would do! Create an id column. $query=Select mysqli_query records Do $rand=rand(1,$mysqli_num_rows($query)). Then $query=SELECT query and then fetch_assoc and flooded))
If the record id's are fairly evenly distributed (no big gaps), then max(id) can be chosen, then the first row with an id greater than max(id)*rand(1).
Instead of id, you can use timestamp entries, taking a string with a timestamp greater than
min(timestamp)+(max(timestamp)-min(timestamp))*rand(1).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question