Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying the inner join of two tables with the same column name, Column 'exName' in field list is ambiguous

I am querying the inner join of three tables using the following query.

Two of the tables have columns named "name1". I am getting the following error.

Column 'exName' in field list is ambiguous

The "name1" columns are foreign key so the information should be identical. Can anyone suggest a compact way around this?

$result = mysql_query("SELECT name1,name2,name3 FROM `table1` INNER JOIN `table2` ON table2.name1=table1.PrimaryKey INNER JOIN `table3` ON table3.name1=table1.PrimaryKey"); 
like image 668
Ben Pearce Avatar asked Feb 23 '13 01:02

Ben Pearce


People also ask

How do I fix the ambiguous column name in SQL?

You may see an error that says something like Column 'id' in field list is ambiguous . This error means that there is a field name that is present in more than one table, so it needs to be scoped with the table name to avoid ambiguity: using orders.id instead of just id will resolve the issue.

What happens when you inner join the same table?

The INNER JOIN selects all rows from both participating tables as long as there is a match between the columns. An SQL INNER JOIN is same as JOIN clause, combining rows from two or more tables.

Is a type of inner join which is based on column having same name?

Natural Join It is a type of inner type that joins two or more tables based on the same column name and has the same data type present on both tables.


2 Answers

You need to qualify your column names with the table names.

 SELECT table1.name1, table2.name1, etc.
like image 139
Vincent Ramdhanie Avatar answered Oct 18 '22 23:10

Vincent Ramdhanie


You need to refer to the columns in your select list as:

SELECT <table name>.name1, <table name>.name2, <table name>.name3

You can also give the tables an alias when you introduce them in the from clause to save some keystrokes and make things cleaner:

SELECT 
     t1.name1
    ,t2.name2
    ,t3.name3
FROM table1 AS t1
INNER JOIN table2 AS t2
    ON t2.name1 = t1.PrimaryKey
INNER JOIN table3 AS t3
    ON t3.name1 = t1.PrimaryKey
like image 38
supergrady Avatar answered Oct 19 '22 00:10

supergrady