用重复的列名在SQL中联接三个表

时间:2018-07-12 01:30:01

标签: sql

我在SQL中有三个表,需要将它们连接在一起,这是一个简化的版本:

表1列

Person ID (pID)
Fav Soccer Team (favST)
Fav Soccer Player (favSP)

表2列

Person ID (pID) 
Fav Soccer Team (favST) 
Fav Soccer Player (favSP)

表3列

Person ID (person_ID)
Person Name (pName)

问题在于每个人都可能同时出现在表1和表2中。您可以举个例子,表1反映了2017年最喜欢的球队和球员,表2反映了2018年最喜欢的球队和球员。

我必须创建一个查询,将所有查询都加入并显示

结果列

Person ID (pID) 
Person Name (pName)
Favourite Soccer Team (favST) 
Favourite Soccer Player (favSP)
Table1/Table2 <--- which table this row of data is from

1 个答案:

答案 0 :(得分:1)

尝试以下操作:

Select
  Table3.person_ID,
  Table3.pName,
  X.favST,
  X.favSP,
  X.tname
From
  Table3
Left join
  (
  Select
    PID,
    FavST,
    FavSP,
    'Table1' as tname
   From
    Table1
  Union
  Select
    PID,
    FavST,
    FavSP,
    'Table2' as tname
   From
    Table2
  )X on x.pId = table3.person_ID;