6

在此先感谢您的帮助:

[People]表有两列:

  • 个人ID
  • 人名

[Marriages]表有三列:

  • 结婚证
  • 个人身份证
  • 个人IDb

我想选择以下列:

  • 结婚证
  • 人名(对于 personIDa)
  • PersonName(用于 personIDb)

我想我需要使用SELECT带有 a 的语句JOIN,但我不确定如何为每个PersonName. 这是我到目前为止所拥有的(这不起作用):

SELECT 
    [Marriages].[MarriageID], 
    [People].[PersonName] AS aName, 
    [People].[PersonName] AS bName  
FROM 
    [Marriages]  
JOIN 
    [People] ON [Marriages].[PersonIDa] = [People].[PersonID]  
JOIN 
    [People] ON [Marriages].[PersonIDb] = [People].[PersonID]  

再次感谢...

4

5 回答 5

8

这是否符合您要完成的任务?

SELECT m.[MarriageID], peopleA.[PersonName] AS aName, peopleB.[PersonName] AS bName  
FROM [Marriages]  M
JOIN [People] peopleA ON m.[PersonIDa] = peopleA.[PersonID]  
JOIN [People] peopleB ON m.[PersonIDb] = peopleB.[PersonID]  
于 2013-01-05T02:18:59.073 回答
2

我认为您正在尝试这样做...

SELECT 
m.[MarriageID], 
pa.[PersonName] AS aName,
pb.[PersonName] AS bName  
FROM [Marriages] m
JOIN [People] pa ON m.[PersonIDa] = pa.[PersonID]  
JOIN [People] pb ON m.[PersonIDb] = pb.[PersonID];
于 2013-01-05T02:18:06.433 回答
1

您将需要类似的东西:

Select MarriageID, a.PersonName, b.PersonName
From Marriages m
Join People a On a.PersonID = m.Person1ID 
Join People b on b.PersonID = m.Person2ID 
于 2013-01-05T02:19:03.893 回答
1

不要忘记您需要什么类型的 JOIN...“INNER JOIN”/“LEFT OUTER JOIN”/“RIGHT OUTER JOIN”/“CROSS JOIN”

SELECT MarriageID, a.PersonName, b.PersonName
FROM Marriages m JOIN People a ON a.PersonID = m.Person1ID 
                 JOIN People b ON b.PersonID = m.Person2ID 
于 2013-01-05T04:20:55.363 回答
-1

谢谢大家; 你的建议很有效。当我应该尝试为 JOIN 语句中的重复表创建别名时,我试图为 SELECT 语句中的重复列创建别名。

对于遇到此问题的其他任何人:

SELECT  
[TABLE1 NAME].[TABLE1 COLUMN],  
(TABLE2 ALIAS1).[TABLE2 COLUMN],  
(TABLE2 ALIAS2).[TABLE2 COLUMN],  
FROM [TABLE1 NAME]  
JOIN [TABLE2 NAME] (TABLE2 ALIAS1) ON [TABLE1 NAME].[TABLE1 MATCHING COLUMN] = (TABLE2 ALIAS1).[TABLE2 MATCHING COLUMN]  
JOIN [TABLE2 NAME] (TABLE2 ALIAS2) ON [TABLE1 NAME].[TABLE1 MATCHING COLUMN] = (TABLE2 ALIAS2).[TABLE2 MATCHING COLUMN]  

别名在 JOIN 语句中创建并应用于 SELECT 语句中使用它的位置,而不是相反。

于 2013-01-05T16:32:46.247 回答