title: What is most efficient way to display random selection of rows from specific MYSQLI results?
body: <p>For my <a href="http://culturepics.org" rel="nofollow">http://culturepics.org</a> site I have a reasonably large table (>30,000 records and growing) which stores basic information about image files, most notably their width and height (px). When a user inputs their chosen dimensions I display images that match (or closely match) that aspect ratio. Currently this is the first '$n' results where $n is higher for smaller images, but I would like to return more results (e.g. 50 matches) and then display $n images randomly chosen from this results set.</p>
  
  <p>My query is currently</p>
  
  <pre><code>"SELECT *, abs(((width/height)-$ratio)) as diff FROM `imagedata` ORDER BY diff ASC LIMIT 0,$n"
  </code></pre>
  
  <p>where <code>$ratio</code> is calculated from the user's input.</p>
  
  <p>Given the size of my table I have read that anything using rand() in MYSQLI will be inefficient. Do I need to look at returning 50 results in my query and then selecting random rows using PHP, and if so can anyone suggest the most suitable method? I'm also a little concerned that calculating <code>diff</code> in the query may be inefficient but it seems to be working fine right now. However, I could always create a new indexed column and populate that when I store image data, if that sounds like a good idea. Thanks</p>