如果我设法在 mysql 中创建以下 View
select id,name,score,total,CALCIT(total - score) as x,(CALCIT(total - score) / total) as per from tblx;
过程CALCIT(total - score)正在计算两次
如何做这样的事情:
select id,name,score,total,CALCIT(total - score) as `x`,`x`/total as per from tblx;
其中 CALCIT 是一个函数
最佳答案
MySQL 将允许您在 ORDER BY, GROUP BY
子句中使用列别名,但您将无法在 SELECT
列表中重用该别名.如果你真的需要这样做,有许多计算值的实例,你可以做一个 self 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
中重做计算更高效,但与任何事情一样,要通过基准测试才能找到答案。
关于mysql - 我可以在查询的许多位置使用列别名吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9362314/