我需要一个连接,从两个不同的表中生成三个具有相同名称的字段。当我尝试运行我的SQL查询时,VS给了我以下错误。
对象" PoliticalFigures"和政治数据" FROM子句中具有相同的公开名称。使用相关名来区分它们。
我一直试图使用" AS"区分这些领域,但我还没有找到一个有效的解决方案。这是我正在运行的SQL查询:
SELECT Countries.Name AS Country, PoliticalFigures.Name AS President, PoliticalFigures.Name AS VicePresident FROM Countries
LEFT OUTER JOIN PoliticalFigures ON Countries.President_Id = PoliticalFigures.Id
LEFT OUTER JOIN PoliticalFigures ON Countries.VicePresident_Id = PoliticalFigures.Id
如果代码中不明显,则这些是表格。
(注意,我的应用程序中的表和字段有不同的名称。我正在推广它们以使这个例子更清晰,希望与其他人更相关。)
(我使用的工具是Visual Web Developer 2010 Express和SQL Server 2008 Express。)
答案 0 :(得分:34)
对PoliticalFigures
的每个引用使用表别名:
SELECT
Countries.Name AS Country,
P.Name AS President,
VP.Name AS VicePresident
FROM
Countries
LEFT OUTER JOIN PoliticalFigures AS P ON Countries.President_Id = P.Id
LEFT OUTER JOIN PoliticalFigures AS VP ON Countries.VicePresident_Id = VP.Id
答案 1 :(得分:19)
为表格提供别名:
SELECT
Countries.Name AS Country,
P.Name AS President,
VP.Name AS VicePresident
FROM Countries
LEFT JOIN PoliticalFigures P ON Countries.President_Id = P.Id
LEFT JOIN PoliticalFigures VP ON Countries.VicePresident_Id = VP.Id
答案 2 :(得分:4)
在SQL标准中,白话'表别名'被称为correlation name
,而白话'列别名'被称为as clause
。看来你有两个术语混淆了。
答案 3 :(得分:2)
您需要在表上使用AS来为它们提供别名:
SELECT Countries.Name AS Country, Pres.Name AS President, Vice.Name AS VicePresident FROM Countries
LEFT OUTER JOIN PoliticalFigures AS Pres ON Countries.President_Id = Pres.Id
LEFT OUTER JOIN PoliticalFigures AS Vice ON Countries.VicePresident_Id = Vice.Id