我覺得ap您正在採取的步驟是:
- 獲取
dcode
爲巴塞羅那到馬德里的路線司機。我們稱之爲Set1。
- 獲取
dcode
司機從馬德里到巴塞羅那。我們稱之爲Set2。
- 最後,得到了
dname
司機,其dcode
在兩個SET1和SET2。
您的SET1查詢:
SELECT dcode FROM ride WHERE rcode IN (
SELECT rcode FROM route WHERE departure = 'Barcelona' AND arrival = 'Madrid'
)
在同一行的查詢SET2是:
SELECT dcode FROM ride WHERE rcode IN (
SELECT rcode FROM route WHERE departure = 'Madrid' AND arrival = 'Barcelona'
)
最後,你需要得到dcode
這在Set1 & inSet2。這將轉換爲查詢:
SELECT dname FROM driver WHERE
dcode IN (
SELECT dcode FROM ride WHERE rcode IN (
SELECT rcode FROM route WHERE departure = 'Barcelona' AND arrival = 'Madrid'
)
)
AND
dcode IN (
SELECT dcode FROM ride WHERE rcode IN (
SELECT rcode FROM route WHERE departure = 'Madrid' AND arrival = 'Barcelona'
)
)
在您的查詢,而不是兩套尋找dcode
,你在兩組尋找rcode
。
改進建議:對於查詢得到dcode
集合,您可以使用內部連接而不是使用嵌套查詢。例如:
SELECT dcode FROM ride INNER JOIN route ON ride.rcode = route.rcode
WHERE departure = 'Barcelona' AND arrival = 'Madrid'
您的查詢是否會導致錯誤或返回沒有結果?我假設有多條路線具有相同的應該返回的rcode。 – hines