Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Selecting the rows having min value of a computed column

The naive way of doing this that comes to mind would be:

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 ));

However the "(SELECT name, levenshtein(name, parameter) as lev FROM my_table)" subquery, which is very expensive (huge table) is repeated twice which seems horribly inefficient.

I somehow though you could write :

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);

But it doesn't seem to work.

Is there a clean way to optimize that query for speed? Did I miss something obvious?

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)

Any input from SQL ninjas would be greatly appreciated ;)

like image 782
Vermillon Avatar asked Sep 10 '10 18:09

Vermillon


People also ask

How do I select a row with minimum value in SQL?

To find the minimum value of a column, use the MIN() aggregate function; it takes as its argument the name of the column for which you want to find the minimum value. If you have not specified any other columns in the SELECT clause, the minimum will be calculated for all records in the table.

How do I find the lowest value in a column in MySQL?

The MIN() function in MySQL is used to return the minimum value in a set of values from the table. It is an aggregate function that is useful when we need to find the smallest number, selecting the least expensive product, etc.

Can you use MIN function in WHERE clause?

The SQL MIN() function with WHERE clauseThe aggregate functions can be used in conjunction with the WHERE clause to gain further insights from our data. One of these is the MIN() function. In SQL, the MIN() function is used to compute the smallest or minimum value of numeric values in a column.

How do you find the minimum value in a table in SQL?

The MIN() function returns the smallest value of the selected column.


1 Answers

select * from
(
SELECT * 
FROM `test`.`test`
)
as temp
where compute_total_price_single=(select min(compute_total_price_single))
;

This is what I did for my problem, since it worked I suspect the following would also work:

SELECT name, lev FROM
    (SELECT name, levenshtein(name, *parameter*) as lev FROM my_table) as my_temp_table
WHERE 
lev = (SELECT MIN(lev));

I'm using MySQL 5.

like image 59
Mzq Avatar answered Nov 02 '22 22:11

Mzq