Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve ambiguous column names when retrieving results?

I have two tables in my database:

NEWS table with columns:

  • id - the news id
  • user - the user id of the author)

USERS table with columns:

  • id - the user id

I want to execute this SQL:

SELECT * FROM news JOIN users ON news.user = user.id  

When I get the results in PHP I would like to get associative array and get column names by $row['column-name']. How do I get the news ID and the user ID, having the same column name?

like image 308
Dan Burzo Avatar asked Jan 10 '09 17:01

Dan Burzo


People also ask

Why column reference is ambiguous?

Explanation: This error occurs when the referenced column can't be resolved unambiguously. This may occur when you have two tables that have columns with the same name.

Why it is showing invalid column name in SQL?

An invalid column name error in SQL means that the column name violates the conditions of the column name. If you reference an object that does not exist in the table or the name exists, but you did not reference it correctly, you will get this error.

What does it mean in SQL when something is ambiguous?

Ambiguous error means that you are calling a certain field in which exist in both Table and the SQL has no idea where to get it.

What is ambiguous error?

Ambiguity errors occur when erasure causes two seemingly distinct generic declarations to resolve to the same erased type, causing a conflict.


1 Answers

You can set aliases for the columns that you are selecting:

$query = 'SELECT news.id AS newsId, user.id AS userId, [OTHER FIELDS HERE] FROM news JOIN users ON news.user = user.id' 
like image 151
Christian C. Salvadó Avatar answered Oct 04 '22 22:10

Christian C. Salvadó