S
S
Snewer2014-04-04 19:42:27
PHP
Snewer, 2014-04-04 19:42:27

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

4 answer(s)
T
Tyranron, 2014-04-04
@Tyranron

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.

D
Dmitry T., 2014-04-04
@tyzhnenko

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;

T
tsisforever, 2014-04-04
@tsisforever

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))

R
Rsa97, 2014-04-04
@Rsa97

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 question

Ask a Question

731 491 924 answers to any question