1

I'm trying to use an SQL alias within a left join. While using the alias in the join, I get the error 'unknown a_alias column in on clause' Could anyone point me in the right direction?

SELECT a as a_alias FROM table_a LEFT JOIN table_b ON a_alias = b

Cheers

1
  • I'm ever so sorry, I accidentally typed 'where' instead of 'on' Commented Jun 11, 2012 at 14:39

3 Answers 3

1

You can't use the alias in a where or a join as it hasn't been evaluated yet. They're only available in aggregates and group by/order by/having clauses IIRC.

Sign up to request clarification or add additional context in comments.

Comments

0

The only aliases you can use in ON are any table aliases; the SELECT clause is first in the grammar, but is (usually) the last processing step; the projection you ask for in the SELECT clause is not available yet. You cannot use column aliases defined in the SELECT clause in an ON clause -- you need to specify the full column name.

3 Comments

Ah, I see. I shortened my query by a lot, the actual code I use is SELECT AES_DECRYPT(column_a, 'key') as a_alias FROM table_a ... That's why I wanted to use an alias
Ended up just selecting the column I needed and decrypting it in the on clause. My problem is solved, thank you! :)
No problem. Note that if you wanted to save the computation time (assuming that MySQL can't optimize away the second call) you could always execute the function in a subquery (SELECT a_alias FROM (SELECT a AS a_alias FROM table_a) AS a_query LEFT JOIN table_b ON a_query.a_alias = table_b.b).
0

If you want to use an alias in a query you can do the following:

SELECT *
FROM 
(
    SELECT a as a_alias
    FROM table_a
) ta
LEFT JOIN table_b 
    ON ta.a_alias = b

You can wrap your SELECT ... FROM in parentheses and then use the table alias and the column alias in your JOIN.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.