[英]SQL Multiple columns same join column
我的旅行表中有一個包含3列的表(當然還有更多):
AirportFrom,AirportTo,AirportFound。
上方的列顯示了機場的ID。 在表Airports中有2列AirportID和AirportName。 我不想顯示機場的ID,而是要顯示AirportNames。
但是當我使用時:
SELECT id
, AirportFrom
, Airports.Airportname
, AirportTo
, Airports.Airportname
, AirportFound
, Airports.Airportname
FROM Travel
LEFT
JOIN Airports
ON AirportTo = Airports.AirportID
-- LEFT JOIN Airports ON AirportFrom = Airports.AirportID
-- LEFT JOIN Airports ON AirportFound = Airports.AirportID
它僅在每列中顯示第一個聯接的機場名稱。 我想顯示3個聯接中每個聯接的機場名稱
每次離開聯接時,為聯接表提供多個別名,並在擁有多個表時聯接它們:
SELECT
Travel.id,
airport_to.Airportname as to_name,
airport_from.Airportname as from_name,
airport_found.Airportname as found_name,
FROM Travel
LEFT JOIN Airports airport_to ON Travel.AirportTo = airport_to.AirportID
LEFT JOIN Airports airport_from ON Travel.AirportFrom = airport_from.AirportID
LEFT JOIN Airports airport_found ON Travel.AirportFound = airport_found.AirportID
編輯:替換表別名中的保留字。 感謝您的提醒!
您的查詢需要表別名(對於同一表的多個聯接)。 然后,請確保對查詢中的所有列使用合格的列名稱。 這可以幫助您編寫正確的查詢,還可以幫助您和其他人了解正在發生的事情。 所以:
SELECT t.id, t.AirportFrom, apt.Airportname,
t.AirportTo, apf.Airportname,
t.AirportFound, apfo.Airportname
FROM Travel t LEFT JOIN
Airports apt
ON t.AirportTo = apt.AirportID LEFT JOIN
Airports apf
ON t.AirportFrom = apf.AirportID LEFT JOIN
Airports apfo
ON t.AirportFound = apfo.AirportID;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.