title: Optimizing slow ORDER BY RAND() query
body: <p>I have a query that is using <code>ORDER BY RAND()</code> but it takes too long and it's getting worse as data is growing.</p>
  
  <p>The query joins two tables and it returns 5 random products and a random image of each product</p>
  
  <h2>Table 1 - Products</h2>
  
  <pre><code>product_id - pk auto-inc
  name 
  description
  </code></pre>
  
  <h3>Data</h3>
  
  <pre><code>1 - product 1 - description
  2 - product 2 - description
  </code></pre>
  
  <h2>Table 2 - ProductImages</h2>
  
  <pre><code>image_id   - pk auto-inc
  product_id - fk index
  filename
  </code></pre>
  
  <h3>Data</h3>
  
  <pre><code>1 - 1 - product 1 image
  2 - 1 - product 1 image
  3 - 1 - product 1 image
  4 - 2 - product 2 image
  </code></pre>
  
  <p>...</p>
  
  <p>I've read <a href="https://stackoverflow.com/questions/4209886/mysql-select-random-row-with-join-from-two-tables">this</a> and <a href="http://jan.kneschke.de/projects/mysql/order-by-rand/" rel="nofollow noreferrer">this</a> but cannot find a way to optimize the query so i'm asking for help.
  Thanks in advance.</p>