所以我有2张桌子
地方
PlaceID varchar PK
PlaceName varchar
行程
TripID int PK
Depart TIME
DepartPlc varchar
ArrivalPlc varchar
ArrivalTime TIME
DepartPlc
和ArrivalPlc
都存储了PlaceID
。
我想从旅行中选择数据,但显示与PlaceName
和DepartPlc
中存储的ID相对应的de ArrivalPlc
数据。
任何人都可以帮助我吗?
我目前有这样的陈述:
SELECT TripID, Depart, PlaceName, ArrivalPlc, ArrivalTime
FROM Trips, Places
WHERE TripID = 'VALUE' AND PlaceName = DepartPlc;
这就像我想要的那样,但当我为ArrivalPlc添加相同的东西显然不起作用...
答案 0 :(得分:6)
使用两个不同的表别名来加入两次
SELECT DPlaces.placeid D_PlaceID,
Aplaces.placeid A_PlaceID
FROM trips t
INNER JOIN places DPlaces
ON t.departplc = DPlaces.placename
INNER JOIN places APlaces
ON t.arrivalplc = aplaces.placename
WHERE t.TripID = 'VALUE'
答案 1 :(得分:3)
您需要在places
子句中使用from
表两次:
select
tripId, depart,
departPlc as departPlaceId, dp.placeName as departPlaceName,
arrivalPlc as arravalPlaceId, ap.placeName as arrivalPlaceName
from
trips as t
inner join places as dp on t.departPlc = dp.placeId
inner join places as ap on t.arrivalPlc = ap.placeId
where
t.tripId = 'VALUE`
请注意,为了清楚起见,我将关系条件从where
子句移动到from
子句(ussing内连接)。这样你就可以保持清晰的分离:关系和过滤器。
答案 2 :(得分:0)
您需要在Trips上进行第二次加入
SELECT t.TripID, t.Depart, d.PlaceName AS DepartPlaceName, a.PlaceName AS ArrivalPlaceName, t.ArrivalTime
FROM Trips t, Places d, Places a
WHERE t.TripID = 'VALUE' AND t.DepartPlc = d.PlaceID AND t.ArrivalPlc = a.PlaceID