我需要一个从两个不同的表中生成三个同名字段的连接。当我尝试运行我的 sql 查询时,VS 给我以下错误。
The objects "PoliticalFigures" and "PoliticalFigures" in the FROM clause have the same exposed names. Use correlation names to distinguish them.
我一直在尝试使用“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
如果从代码中看不出来,这些就是表格。
- 国家:Id、姓名、President_Id、VicePresident_Id。
- 政治人物:身份证、姓名。
- 连接表:国家、总统、副总统
(请注意,我的应用程序中的表和字段有不同的名称。我将它们概括为使这个示例更清晰并且希望与其他人更相关。)
(我使用的工具是 Visual Web Developer 2010 Express 和 SQL Server 2008 Express。)
最佳答案
为每个对 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
关于sql - 如何更正此 sql 连接上的相关名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8956577/