如何在sql server中对单个表进行两次内连接

时间:2014-06-28 07:00:45

标签: sql-server

我在sql server中有两个表

City_Master(
ID bigint,
Name  nvarchar(50)
)
Tour_Details(
ID bigint,
From_City bigint,
To_City bigint,
Details nvarchar(max),
Cost nvarchar(100),
Tour_Name nvarchar(100),
Duration nvarchar(max))

Tour_Details表From_City和To_City中的列来自City_Master表。我想选择在Tour_Details表的From_City和To_City列中的ID城市名称。

我使用了以下的SQL查询

SELECT Tour_Details.ID, Tour_Details.Tour_Name, Tour_Details.From_City, Tour_Details.To_City, Tour_Details.Cost, 
   Tour_Details.Details,Tour_Details.Duration, City_Master.Name as City FROM Tour_Details INNER JOIN
   City_Master ON Tour_Details.From_City = City_Master.ID ORDER BY Tour_Details.ID DESC

但它只返回一个城市名称,但在tour_Details表格列中有两个城市ID,如From_City,To_City。我想要两个城市的名字。请任何人帮助我

1 个答案:

答案 0 :(得分:2)

试试这个

SELECT Tour_Details.ID, Tour_Details.Tour_Name, Tour_Details.From_City, Tour_Details.To_City, Tour_Details.Cost, 
Tour_Details.Details,Tour_Details.Duration, B.Name as FromCityName, A.Name as ToCityName 
FROM Tour_Details 
INNER JOIN City_Master B ON B.ID  = Tour_Details.From_City
INNER JOIN City_Master A ON A.ID = Tour_Details.To_City 
ORDER BY Tour_Details.ID DESC