如果我设法在mysql中创建以下视图
select id,name,score,total,CALCIT(total - score) as x,(CALCIT(total - score) / total) as per from tblx;
过程CALCIT(总得分)正在计算两次
如何做这样的事情:
select id,name,score,total,CALCIT(total - score) as `x`,`x`/total as per from tblx;
其中CALCIT是一个函数
答案 0 :(得分:3)
MySQL允许您在ORDER BY, GROUP BY
子句中使用列别名,但是您将无法在SELECT
列表中重用别名。如果你真的需要这样做,有很多计算值的实例,你可以做一个自我JOIN
来产生计算。
SELECT
id,
name,
score,
total,
x,
x / total AS per
FROM tblx JOIN (
/* Subquery JOIN which performs the calculation */
SELECT CALCIT(total - score) AS x FROM tblx xcalc
) ON tblx.id = xcalc.id
这种方法可能比在一个SELECT
中重做计算更有效,但与任何事情一样,基准来找出。
答案 1 :(得分:2)
更好的是你可以使用内部查询 -
select id,
name,
score,
total,
X,
X/total as per
from (
select id,
name,
score,
total,
CALCIT(total - score) as X from tblx
)
答案 2 :(得分:2)
尝试这样的事情:
select *, x/total from (
select id,name,score,total,CALCIT(total - score) as x from tblx;
) as tblx