Vainglory07
Vainglory07

Reputation: 5273

Use Table Alias as Column in MySQL

I have a query like this:

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

Is there a way where I can use my previously defined alias as column so it will be like:

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

Or any other solution where I will not re-code any of the expression in this query.

Upvotes: 0

Views: 100

Answers (3)

Bharat Ranpariya
Bharat Ranpariya

Reputation: 1253

Their can be many ways, but as per i know, you can do this by using subquery like this. you will get all your alias as column when you make main query as subquery and use it as per your requirement.

Check this tutorial for more stuff : 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;

Upvotes: 1

Vainglory07
Vainglory07

Reputation: 5273

Use 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;

Upvotes: 2

Eduard Uta
Eduard Uta

Reputation: 2607

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

Upvotes: 2

Related Questions