I
I
Ilya2015-09-28 14:18:29
MySQL
Ilya, 2015-09-28 14:18:29

How to pull a random entry from a tablet?

I know this way:
select * from table order by rand() limit 1
But the execution speed is depressing, but what do you use?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alex Safonov, 2015-09-28
@az2rt

Change `table` to the name of your table, and tell me if there's a speed boost.

SELECT tab1.`id`  FROM `table` AS tab1
  JOIN
    (SELECT
      (  RAND() * (SELECT MAX(id) FROM `table`) ) 
    AS id )
  AS tab2
 WHERE tab1.id >= tab2.id
 ORDER BY tab1.id ASC
 LIMIT 1;

O
Optimus, 2015-09-28
Pyan @marrk2

$id = rand(1....10000)
select * from where id=$id

S
Stanislav Pochepko, 2015-09-28
@DJZT

MySql does not have a normal random selection functionality. So use rand()

$rez = mysql_query("SELECT id from table")
$id = array_rand(mysql_fetch_array($rez))['id'];

This code will exclude non-existent id in the table

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question