2017-07-17 102 views
0

我對sql很新,而且我正在努力創建一個查詢。我有兩個表:SQL加入初學者

  • 或CharacterId
  • 姓氏
  • 性別

夫婦

  • 政變LEID
  • femaleID
  • maleID

現在我試圖把它一起這樣的:

  • femaleFName
  • femaleLName
  • maleFName
  • maleLName

我想:

SELECT character.firstname AS femaleFName, character.lastname AS femaleLName 
FROM Couple INNER JOIN Character ON Character.characterID = Couple.femaleID 

但我現在與第二個連接掙扎。

回答

1

您只需要再次加入表格。爲此,您必須提供別名,以便表格不會混淆。

SELECT 
cf.firstname AS femaleFName, cf.lastname AS femaleLName, 
mf.firstname AS maleFName, mf.lastname AS maleLName 
FROM Couple 
INNER JOIN Character AS cf ON cf.characterID = Couple.femaleID 
INNER JOIN Character AS mf ON mf.characterID = Couple.maleID 

關鍵字AS不是強制性的,但可以省略。

0

添加另一個JOIN像下面。這裏c是用於區別第二次連接的表別名

SELECT character.firstname AS femaleFName, character.lastname AS femaleLName 
FROM character INNER JOIN Couple ON Character.characterID = Couple.femaleID 
INNER JOIN Couple c ON Character.characterID = c.maleID 
0

您需要使用自連接來獲得所需的結果。根據需要使用以下查詢獲取結果。

Select cf.firstname as femaleFName, 
cf.lastname as femaleLName, 
cm.firstname as maleFName, 
cm.lastname as maleLName 
from Couple c 
inner join Character cf on c.femaleID = cf.characterID 
inner join Character cm on c.maleID= cm.characterID 

我希望這對你有所幫助。

謝謝!