didiadas29
didiadas29

Reputation: 42

SQL Query with Alias and Re-use it. How does it work?

I have some query that using alias 'as' for example:

select (TABLE_A.NAME) as NAME_A from TABLE_B where id = 1

What I am trying to do is re-call/re-use the NAME_A as next column like:

select (TABLE_A.NAME) as NAME_A, (NAME_A+"ME") as NAME_B from TABLE_B where id = 1

How can I do that?

Upvotes: 0

Views: 47

Answers (2)

lw493
lw493

Reputation: 13

You can use a subquery instead. A workaround would be something like:

select NAME_A, (NAME_A+"ME") as NAME_B
from(
    select (TABLE_A.NAME) as NAME_A
    from TABLE_A
        where id = 1
    )

Upvotes: 0

Shadow
Shadow

Reputation: 34232

You cannot reference a select list alias in the same select list. As MySQL documentation on select list aliases says:

A select_expr can be given an alias using AS alias_name. The alias is used as the expression's column name and can be used in GROUP BY, ORDER BY, or HAVING clauses.

You need to wrap the aliased select expression into a subquery and you can use the aliased expression in the outer query. Or just simply refer to the field under its original name.

Upvotes: 1

Related Questions