我有这些列的表VISITS
Visit_ID , Location_ID , Next_Location_ID
----------
0001 , 101 , 102
0002 , 105 , 102
0003 , 102 , 105
----------
并且有一个表格,其中包含名称和其他信息的位置详细信息
Location
location_id , Name
----------
101 , US
102 , UK
.
.
.
105 , CA
----------
我的问题是如何编写SQL语句来检索这些信息
Visit_ID , Location_ID , Next_Location_ID
0001 , US , UK
0002 , CA , UK
0003 , UK , CA
答案 0 :(得分:1)
加入location
表两次:
select v.Visit_ID, l1.Name, l2.Name
from VISITS v
join Location l1 on l1.location_id = v.Location_ID
join Location l2 on l2.location_id = v.Next_Location_ID
答案 1 :(得分:1)
将visits
表加入location
表两次 - 对visits
中的每个外键加一次,如下所示:
select v.*, a.name location, b.name next_location
from visits v
join location a on a.location_id = v.location_id
join location b on b.location_id = v.next_location_id
执行此操作时,您必须使用表别名(此处我已使用" a"" b")来区分在查询中互相乌鸦。