Answer the question
In order to leave comments, you need to log in
How to select a random record from MySQL database without using primary key and order by rand()
There was such a problem, there is a database that contains users (users who installed the VKontakte application, to be precise), as the Primary key, the user id in the social network is used, which can be considered a random number. You need to select one random user from the database. There are a lot of users in the database, so order by rand() is too expensive to use, generating a random number and choosing a record with the same id will also fail, given that the ids are out of order. How to be in such a situation? And at the same time, what if you need several random users?
Answer the question
In order to leave comments, you need to log in
The first thing that comes to mind is to play around with limit, for example limit <random number>,<sample size>
The best solution is to take a random in the range in which the primary key lies - and get a record whose key is greater than or equal to this random. Like this:
SELECT * FROM my_table WHERE pk_column >= (SELECT FLOOR( MAX(pk_column) * RAND()) FROM my_table) ORDER BY pk_column LIMIT 1;
hudson.su/2010/09/16/mysql-optimizaciya-order-by-rand/
habrahabr.ru/blogs/mysql/55864/
habrahabr.ru/blogs/mysql/54176/
get a uRAND field in the table and once a day sit there the true RAND
after which SELECT * FROM table WHERE uRAND<somerandvalue ORDER BY uRAND DESC LIMIT 1
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question