我相信我的问题在哪里,但我不确定如何解决它。 我想找一个出发地点与抵达地点不同的旅行。但是我编写代码的方式使得它只返回具有相同出发和到达位置的集合。我怎么能解决这个问题?我想找一个离开波士顿的旅行,然后到达拿骚,同时避免使用像旅行这样的代码。 DepartureLocCode =" BOS"
SELECT name
FROM staff, trip, locations
WHERE trip.TripNum = staff.TripNum AND staff.DATE = trip.DATE AND trip.DATE = '2015-08-14'
AND (trip.ArrivalLocCode = locations.LocationCode AND locations.Location = "Nassau")
AND (trip.DepartureLocCode = locations.LocationCode And locations.Location = "Boston");
答案 0 :(得分:3)
首先:从不在FROM
子句中使用逗号。 始终使用正确的,明确的JOIN
语法。如果您正在学习SQL,则尤其如此。
但是,你的主要问题是你需要两个连接:
SELECT name
FROM staff s JOIN
trip t
ON t.TripNum = s.TripNum JOIN
locations la
ON t.ArrivalLocCode = la.LocationCode JOIN
locations ld
ON t.DepartureLocCode = ld.LocationCode
WHERE t.DATE = '2015-08-14' AND
la.Location = 'Nassau' AND
ld.Location = 'Boston';
答案 1 :(得分:1)
您需要像这样两次加入位置表。 (我使用了现代显式JOIN语法)
SELECT name
FROM staff s
inner join trip t on t.TripNum = s.TripNum AND s.DATE = t.DATE
inner join locations l1 on t.ArrivalLocCode = l1.LocationCode
inner join locations l2 on t.DepartureLocCode = l2.LocationCode
WHERE t.DATE = '2015-08-14'
AND l1.Location = 'Nassau'
AND l2.Location = 'Boston';
答案 2 :(得分:1)
您需要两次加入位置表。
我不是隐式联接的粉丝,它妨碍了可读性恕我直言,所以我已经明确了你的联接。
SELECT name
FROM staff s
JOIN trip t ON t.TripNum = staff.TripNum
JOIN locations l1 ON t.ArrivalLocCode = l1.locationCode
JOIN locations l2 ON t.DepartureLocCode = l2.locationCode
WHERE s.DATE = t.DATE
AND t.DATE = '2015-08-14'
AND l1.location = 'Nassau'
AND l2.location = 'Boston'