MySQL where-clause 中的计算列 - 性能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16068662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculated column in where-clause - performance
提问by Raphael Jeger
Since you can't use a calculated column in a where-clause in MySQL like this:
由于您不能像这样在 MySQL 的 where 子句中使用计算列:
SELECT a,b,c,(a*b+c) AS d FROM table
WHERE d > n
ORDER by d
you have to use
你必须使用
SELECT a,b,c,(a*b+c) AS d FROM table
WHERE (a*b+c) > n
ORDER by d
Is the calculation (in that example "(a*b+c)" executed once per row or twice? Is there a way to make it faster? I find it strange it's possible to ORDER on the column but not to have a WHERE-clause.
计算(在那个例子中“(a*b+c)”是每行执行一次还是两次?有没有办法让它更快?我觉得很奇怪,可以在列上进行 ORDER 但没有 WHERE-条款。
回答by Barmar
You can use HAVING to filter on a computed column:
您可以使用 HAVING 对计算列进行过滤:
SELECT a,b,c,(a*b+c) AS d, n FROM table
HAVING d > n
ORDER by d
Note that you need to include n
in the SELECT clause for this to work.
请注意,您需要包含n
在 SELECT 子句中才能使其工作。
回答by Walid
You could do this:
你可以这样做:
SELECT a,b,c,d FROM
(SELECT a,b,c,(a*b+c) AS d) AS tmp
WHERE d > n
ORDER BY d
But I am not sure what performance implications it could have.
但我不确定它可能对性能产生什么影响。