EasyE
EasyE

Reputation: 580

SQL statement is giving me the following error message Ambiguous column name

Background

I am a bit new to the whole JOIN concept of SQL and trying to write a SQL statement which will get a country's name based on President ID which is in another table, that later points at another table that contains the country's name.

Tables

[President]

ID | PresidentID | Name | Population Governed
1    3             ME     1,000,000,000

[CountryPopulation]

ID |PresidentID| Population Number| CountryID
1   3             1,000,000,000      12

[CountryName]

ID | CountryID | CountryName
3    12            USA

Problem: I have written a SQL statement where I am trying to to get the country's name based on the president ID, however my statement is showing an error:

Ambiguous column name 'PresdientID'.

SQL statement

SELECT
    PresidentID
FROM 
    President A 
INNER JOIN 
    CountryPopulation B ON A.PresdientID = B.PresdientID 
WHERE 
    B.CountryID IN (SELECT CountryName 
                    FROM CountryName 
                    WHERE CountryID = B.CountryID)

Upvotes: 0

Views: 310

Answers (2)

STLDev
STLDev

Reputation: 6174

The field you've selected, PresidentID is ambiguous.You need to specify which table you want to supply the value for PresidentID, like this:

Select
  A.PresdientID
  From President A INNER JOIN 
  CountryPopulation B ON A.PresdientID = B.PresdientID 
  WHERE B.CountryID IN (SELECT CountryName FROM CountryName WHERE CountryID = B.CountryID)

EDIT

Your question states that you're trying to get the CountryName based on the PresidientID value.

If you know the PresidientID value, I would think you'd simply do this:

DECLARE @PresidientID INT = 3
SELECT cn.CountryName
    FROM CountryName cn JOIN CountryPopulation cp ON cn.CountryID = cp.CountryID
    WHERE cp.PresidientID = @PresidientID;

That said, it looks like your database design may be incorrect. It seems that there are quite a few "ID" fields sprinkled around. For instance, your President table contains both an ID field and a PresidientID field; also your CountryName table contains both an ID field and a CountryID field. Also, you have the same information in multiple tables (population number, population governed).

Would it not be better to put all of the country attributes into a single table named Country? Consider this:

CREATE TABLE [Country](
    [ID] int IDENTITY(1,1) NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Population] INT,
    [PresidentID] INT  -- Foreign Key to president
)

CREATE TABLE [President](
    [ID] int IDENTITY(1,1) NOT NULL,
    [PresidentName] nvarchar(100) NOT NULL
)

Upvotes: 2

Jeffrey Van Laethem
Jeffrey Van Laethem

Reputation: 2651

SQL Server is unsure whether you want to return A.PresidentID or B.PresidentID. You need to specify even though the values would be the same in this case.

Upvotes: 2

Related Questions