2012-02-20 51 views
0

如果我设法使如下因素视图在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是一个函数

回答

2

尝试是这样的:

select *, x/total from (
    select id,name,score,total,CALCIT(total - score) as x from tblx; 
) as tblx 
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重做计算更好的性能,但至于用什么,基准一探究竟。

2
更好

可以使用内部查询 -

select id, 
     name, 
     score, 
     total, 
     X, 
     X/total as per 
from (
     select id, 
       name, 
       score, 
       total, 
       CALCIT(total - score) as X from tblx 
    ) 
相关问题