在MySQL中使用表别名作为列

时间:2014-11-14 06:08:27

标签: php mysql

我有这样的查询:

select a,b, (a+b) as c, (a-b) as d, (a+b)*-1 as e, (a+b)/(a-b) as f from test;

有没有办法可以将我以前定义的别名用作列,这样就像:

(a+b)/(a-b) as f from test c/d as f from test

或者我不会重新编码此查询中的任何表达式的任何其他解决方案。

3 个答案:

答案 0 :(得分:4)

使用User-Defined Variables

SELECT a,b, 
    @c := (a+b) as c, 
    @d := (a-b) as d, 
    @c*-1 as e, 
    @c/@d as f
FROM test;

答案 1 :(得分:2)

select *
from (
 select a,b, (a+b) as c, (a-b) as d, (a+b)*-1 as e, (a+b)/(a-b) as f 
 from test
) s

答案 2 :(得分:1)

他们可以有很多种方式,但据我所知,你可以通过使用这样的子查询来做到这一点。 当您将主查询作为子查询并按照您的要求使用它时,您将获得所有别名作为列。

查看本教程以获取更多内容:http://www.mysqltutorial.org/mysql-subquery/

select a,b,c,d,e,f form 
 (select a,b, (a+b) as c, (a-b) as d, (a+b)*-1 as e, (a+b)/(a-b) as f from test)
x;