Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous Column Reference with an AS alias

I am unsure as to how to resolve an ambiguous column reference when using an alias.

Imagine two tables, a and b that both have a name column. If I join these two tables and alias the result, I do not know how to reference the name column for both tables. I've tried out a few variants, but none of them work:

Attempt 1

SELECT a.name, b.name
FROM (a INNER JOIN b ON a.id = b.id) AS x

This doesn't work as a and b are out of scope.

Attempt 2

SELECT x.a.name, x.b.name
FROM (a INNER JOIN b ON a.id = b.id) AS x

SQL syntax doesn't work like that.

Attempt 3

SELECT x.name, x.name
FROM (a INNER JOIN b ON a.id = b.id) AS x

That's just plain ambiguous!

I'm all out of ideas - any help would be much appreciated.

like image 516
Jack Avatar asked Oct 21 '12 23:10

Jack


People also ask

How can you fix an ambiguous column reference error?

One of the simplest ways to solve an “ambiguous name column” error — without changing column name — is to give the tables you want to join an alias. This sends a clear information to the SQL Machine the columns are different.

How do you resolve ambiguous column names?

Ignore the id column as this is an auto-increment column. If we attempt to run a join in the two tables: select full_name, lang, full_name, salary from my_table x inner join my_table_1 y ON x.id = y.id; The above query will return an “ambiguous column name” error.

How do I give an alias a column name?

You can declare an alias for any column in the select list of the Projection clause. The GROUP BY clause can reference the column by its alias. This temporary name is in scope only while the SELECT statement is executing.


1 Answers

don't enclose it with parenthesis since (a INNER JOIN b ON a.id = b.id) is not a complete query.

SELECT  a.name AS A_Name, 
        b.name AS B_Name
FROM    a INNER JOIN b 
           ON a.id = b.id

or (assuming) if you have longer tables names and you want to make it short,

SELECT  a.name AS A_Name, 
        b.name AS B_Name
FROM    longTableNameA a 
        INNER JOIN longTableNameB b 
           ON a.id = b.id
like image 116
John Woo Avatar answered Sep 27 '22 17:09

John Woo