Minor query optimization - calculated column reuse?

Minor query optimization - calculated column reuse?

am 21.07.2006 06:40:03 von ksjayhawk

This isn't very important to me, but my brain is arguing that there is
an elegant way of performing the below "cho+protein+fat" calculation --
without repeating the calculations many times (below is just a simple
version of the problem at hand).

I attempted to select "cho+protein+fat" as a new column name, and then
use that column name as the demoniator in the percentage calculations,
but that failed. Of course, that doesn't work in MySQL, as the column
name is not seen.

My second thought was to join a table that calculates the
(cho+protein+fat) calculation with itself (a self-join), but I'm
thinking that it might be inefficient with thousands of rows.

Any quick ideas, or should I be happy?


Code:
SELECT
( cho/(cho+protein+fat) ) as choPercent,
( protein/(cho/(cho+protein+fat) ) AS proteinPercent,
( fat/(cho/(cho+protein+fat) ) AS fatPercent
FROM
food_table