mirza
mirza

Reputation: 5793

Why that query isn't working as i expected ?

SELECT 3 AS x, 5 as y, (x+y) as z

The result what i expect;

x  y  z
3  5  8

The result what i get;

#1054 - Unknown column 'x' in 'field list' 

Upvotes: 1

Views: 78

Answers (6)

Azodious
Azodious

Reputation: 13872

it's possible that z is defined by query engine before x and y. that means z exists before x and y. and hence the error.

Upvotes: 0

TecHunter
TecHunter

Reputation: 6131

because you can't use your alias X newly created as part of the selector. Use your constant instead since you don't need the alias or a temporary table like other answers.

If your real problem is different please post it, maybe you are simply thinking this wrong

SELECT 3 AS x, 5 as y, (3+5) as z

Upvotes: 0

newtover
newtover

Reputation: 32094

SELECT @x:=3 as x, @y:=5 as y, (@x + @y) as z;

Upvotes: 1

Henrik
Henrik

Reputation: 3704

Why would you like to do this?

Since your query uses constants, this works fine.

SELECT 3 as x,5 as y,(3+5) as z;

Upvotes: 0

gbn
gbn

Reputation: 432261

The SELECT clause (and column aliases) are evaluated at the same time and in no particular order. That is, at the same point you want z, the columns x and y do not exist yet.

SELECT
   (x+y) as z
FROM
    (
    SELECT 3 AS x, 5 as y
    ) t;

Upvotes: 2

Mitch Wheat
Mitch Wheat

Reputation: 300559

You can't refer to a column alias that way. Try

SELECT (tmp.x + tmp.y) as z FROM (SELECT 3 AS x, 5 as y) tmp

Ref.: Subqueries in the FROM Clause

Upvotes: 3

Related Questions