Note that there are some explanatory texts on larger screens.

plurals
  1. POReturning random rows from mysql database without using rand()
    primarykey
    data
    text
    <p>I would like to be able to pull back 15 or so records from a database. I've seen that using <code>WHERE id = rand()</code> can cause performance issues as my database gets larger. All solutions I've seen are geared towards selecting a single random record. I would like to get multiples.</p> <p>Does anyone know of an efficient way to do this for large databases?</p> <p>edit:</p> <p><strong>Further Edit and Testing:</strong></p> <p>I made a fairly simple table, on a new database using MyISAM. I gave this 3 fields: <code>autokey</code> (unsigned auto number key) <code>bigdata</code> (a large blob) and <code>somemore</code> (a medium int). <strong>I then applied random data to the table and ran a series of queries using Navicat. Here are the results:</strong></p> <p><code>Query 1: select * from test order by rand() limit 15</code></p> <pre><code> Query 2: select * from test join (select round(rand()*(select max(autokey) from test)) as val from test limit 15) as rnd on rnd.val=test.autokey;` </code></pre> <p>(I tried both select and select distinct and it made no discernible difference)</p> <p>and:</p> <pre><code>Query 3 (I only ran this on the second test): SELECT * FROM ( SELECT @cnt := COUNT(*) + 1, @lim := 10 FROM test ) vars STRAIGHT_JOIN ( SELECT r.*, @lim := @lim - 1 FROM test r WHERE (@cnt := @cnt - 1) AND RAND(20090301) &lt; @lim / @cnt ) i </code></pre> <pre> ROWS: QUERY 1: QUERY 2: QUERY 3: 2,060,922 2.977s 0.002s N/A 3,043,406 5.334s 0.001s 1.260 </pre> <p>I would like to do more rows so I can see how query 3 scales, but at the moment, <strong>it seems as though the clear winner is query 2</strong>.</p> <p>Before I wrap up this testing and declare an answer, and while I have all this data and the test environment set up, <strong>can anyone recommend any further testing?</strong></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload