INNER JOIN,其中两个具有相同字段的相同表

时间:2019-01-28 18:40:56

标签: sql sql-server

因此,我正在为公共汽车预订系统,[Booking]表中有一些外国ID。当我意识到“ CollectionID”和“ DestinationID”均来自[Location]表时,​​我试图在DataGridView中显示与用户相关的数据。

从本质上讲,[Booking]表包含CollectionID和DestinationID,它们均作为外键来自[Location]表。您不能两次选择相同的集合和目的地。

我尝试了内部连接,结果是一个错误,我还尝试了别名,第一个[Location]表名为LOC1,第二个[Location]表LOC2

SELECT Booking.BookingID, Location.Name, Location.Name, FROM Booking 
INNER JOIN Location 
ON Booking.CollectionID = Location.LocationID 
INNER JOIN Location 
ON Booking.DestinationID = Location.LocationID

结果是:“ FROM子句中的对象“ Location”和“ Location”具有相同的公开名称。使用相关名称来区分它们。”

1 个答案:

答案 0 :(得分:5)

您需要别名!

SELECT b.BookingID, lc.Name, ld.Name
FROM Booking b INNER JOIN
     Location lc
     ON b.CollectionID = lc.LocationID INNER JOIN
     Location ld
     ON b.DestinationID = ld.LocationID;