MySQL:选择具有计算列最小值的行
我想到的天真的做法是:
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 ));
然而,“(SELECT name, levenshtein(name, parameter) as lev FROM my_table)”子查询非常昂贵(巨大的表)是重复两次,这似乎效率极低。
我不知何故虽然你可以写:
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);
但它似乎不起作用。
有没有一种干净的方法来优化查询速度?我错过了一些明显的事情吗?
我必须依赖临时表吗? (由于开销/复杂性,试图避免它,因为它们似乎不适合非常频繁/并发的查询)
来自 SQL 忍者的任何输入将不胜感激;)
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 ;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这就是我为我的问题所做的,因为它有效,我怀疑以下内容也有效:
我正在使用 MySQL 5。
This is what I did for my problem, since it worked I suspect the following would also work:
I'm using MySQL 5.
如果您只是想获取具有最小值的一行,您可以这样做:
If you're just trying to get one row with the minimum value, you could do: