开发者

Same Query MySQL User Defined Variables

I'm attempting to use MySQL's user defined variables, but due to restrictions I can't use them in the same way as it demonstrates, where one query sets the variable and a second uses it. My requirement is to be able to use it multiple times in a query.

Consider the following:

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

It'd be really nice to only run the Total calculation once, and then use the result multiple times throughout the query. Right now, the only way I've gotten it to work in one query is to rerun it for every place it's used as Total returns an er开发者_StackOverflowror saying an unknown column has been used.


Imbed the total calculation in a sub-query...

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

Note: The sub-query (inline-view) is expanded by MySQL when generating it's PLAN. Putting brackets around the query doesn't necessarily mean you're forcing it to be stupidly inefficient :)


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

So basically, do your calculation in a nested SELECT type query in the FROM clause and give it a name of total than you can then use else where in your query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜