我的表中有一个包含3列的表Travel(当然还有更多):
AirportFrom, 机场至, AirportFound。
上面的列显示来自机场的ID。在表中,机场是2列AirportID和AirportName。 我想显示机场名称,而不是显示机场的ID。
但是当我使用时:
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个连接中每个连接的机场名称
答案 0 :(得分: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
编辑:替换表别名中的保留字。谢谢你的提醒!
答案 1 :(得分:1)
您的查询需要表别名(对于同一个表的多个连接)。然后,确保为查询中的所有列使用限定列名。这有助于您编写正确的查询,它可以帮助您和其他人了解正在发生的事情。所以:
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;