S
S
SimBioT192016-02-21 14:57:43
PHP
SimBioT19, 2016-02-21 14:57:43

How to solve the sampling problem?

I use this query to select 14 random records:

"SELECT r1.name FROM `objects` AS r1 JOIN (SELECT CEIL(RAND() * (SELECT MAX(id) FROM `objects`)) AS id)  AS r2 WHERE r1.id >= r2.id  ORDER BY r1.id ASC LIMIT 14

The problem is this: if there are only 100 records and this "code" RAND() * (SELECT MAX(id) FROM `objects`)returns 98 , then naturally only 2 records will be selected, instead of the 14 required, but you always need 14.
I also draw your attention to the fact that there are not 100 records, but only the maximum id is 100, i .e. this principle SELECT MAX(id)-14does not apply.
What should be the query to always select 14 random records?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
I
Igor, 2016-02-21
@unitby

Need 14 records in a row starting with a random one?

V
Vladislav Yandimirkin, 2016-02-21
@vlaad360

Isn't it better to use php to take 14 random numbers from the range in this case, and then just pull them out of the database?

A
Aleksey Ratnikov, 2016-02-21
@mahoho

Remove JOIN and add
ORDER BY RAND() LIMIT 14;

P
Paul Denisevich, 2016-02-21
@deniamnet

I draw your attention to the fact that it is ORDER BY RAND()unrealistically slow thing on a large number of records.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question