title: MySQL: Selecting the rows having min value of a computed column
body: <p>The naive way of doing this that comes to mind would be:</p>
  
  <pre><code>SELECT name, lev FROM
  (SELECT name, levenshtein(name, *parameter*) as lev FROM my_table)
  WHERE 
  lev = (SELECT MIN(lev) FROM 
  (SELECT name, levenshtein(name, *parameter*) as lev FROM my_table ));
  </code></pre>
  
  <p>However the "(SELECT name, levenshtein(name, <em>parameter</em>) as lev FROM my_table)" subquery, which is very expensive (huge table) is repeated twice which seems horribly inefficient.</p>
  
  <p>I somehow though you could write :</p>
  
  <pre><code>SELECT name, lev FROM
  (SELECT name, levenshtein(name, *parameter*) as lev FROM my_table) as my_temp_table
  WHERE 
  lev = (SELECT MIN(lev) FROM my_temp_table);
  </code></pre>
  
  <p>But it doesn't seem to work. </p>
  
  <p>Is there a clean way to optimize that query for speed? Did I miss something obvious?</p>
  
  <p>Do I have to rely on temporary tables?
  (trying to avoid it due to the overhead/complexity as they don't seem appropriate for very frequent/concurrent queries)</p>
  
  <p>Any input from SQL ninjas would be greatly appreciated ;) </p>