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 ;)
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.
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.
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.
The MIN() function returns the smallest value of the selected column.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With