E
E
Evgeny Sheleg2011-11-13 22:52:13
MySQL
Evgeny Sheleg, 2011-11-13 22:52:13

Selecting a random field in MySQL

Hello.

Until recently, I used the ORDER BY rand () crutch, but as the table grows, its speed drops.

It is required to display a random field. Records are fragmented (id is out of order and contains holes).

If it somehow simplifies the task, I use ZF.

Answer the question

In order to leave comments, you need to log in

6 answer(s)
W
winnie, 2011-11-13
@winnie

Let A be the result of SELECT MAX(id) FROM `my_table` (it can be stored separately in key-value storage and sometimes updated)
Generate a number from 1 to A inclusive, let it be B on the client side (in this case, the php application ).
And select the first entry whose id >= B (SELECT `pole` FROM `my_table` WHERE `id` >= B LIMIT 1)
Try it. Should help.

V
vart, 2011-11-14
@vart

There was already such a question:
habrahabr.ru/qa/5525/
And topics on this topic:
habrahabr.ru/blogs/mysql/54176/
habrahabr.ru/blogs/mysql/55864/
habrahabr.ru/blogs/mysql/104366/

E
edogs, 2011-11-13
@edogs

1) Zabatsat table id<->realid. You can fill it very quickly with insert into select from. Accordingly, the id in it will not be fragmented and it will be very easy to select.
2) You can do the same as in item 1, making a table simply from realid, filling it in the same way, and randomly shuffle it. And choose a random number by positioning with the help of a limit, having previously generated a random number based on the number of records.

B
betal, 2011-11-14
@betal

If you understand the task correctly, you need to get 1 random row from the table, where ids can be with holes.
Offhand LIMIT RAND($max),1

E
EugeneOZ, 2011-11-14
@EugeneOZ

This will be fast and not afraid of inconsistent ID sequences
max = "SELECT COUNT(*) FROM `TABLE` (can be cached)
$random_start = mt_rand(0, max-1);
result = SELECT * FROM `TABLE` LIMIT "".$random_start.",1

P
porohnya, 2011-11-14
@porohnya

Keep gaps

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question