简体   繁体   中英

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)

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.

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM