我正在尝试使用MySQL's user defined variables,但由于限制,我无法以与演示相同的方式使用它们,其中一个查询设置变量,第二个使用它。我的要求是能够在查询中多次使用它。
请考虑以下事项:
SELECT (Some Really Taxing Calculation) AS Total FROM Purchases
WHERE Total < 55 AND itemName = "Bananas"
OR Total > 90 AND itemName = "Apples"
OR Total = 30 AND itemName = "Peaches"
ORDER BY Total
仅运行Total
计算一次非常好,然后在整个查询中多次使用结果。现在,我在一个查询中使用它的唯一方法是为每个使用它的地方重新运行它,因为Total
返回一个错误,表示已经使用了未知列。
答案 0 :(得分:1)
在子查询中嵌入总计算...
SELECT
Total
FROM
(SELECT (Some Really Taxing Calculation) AS Total, * FROM Purchases) AS Purchases
WHERE Total < 55 AND itemName = "Bananas"
OR Total > 90 AND itemName = "Apples"
OR Total = 30 AND itemName = "Peaches"
ORDER BY
Total
注意:生成它的PLAN时,MySQL会扩展子查询(内联视图)。在查询周围加上括号并不一定意味着你强迫它愚蠢地低效:)
答案 1 :(得分:0)
SELECT *, total.Value
FROM Purchases, (SELECT COUNT(*) as Value .... Some Really Taxing Calculation) total
WHERE Total < 55 AND itemName = "Bananas"
OR Total > 90 AND itemName = "Apples"
OR Total = 30 AND itemName = "Peaches"
ORDER BY Total
所以基本上,在FROM子句中的嵌套SELECT类型查询中进行计算,并给它一个总名称,然后在查询中使用else。