[英]SQL Multiple columns same join column
I have a table with 3 columns in my table Travel (and of course some more): 我的旅行表中有一个包含3列的表(当然还有更多):
AirportFrom, AirportTo, AirportFound. AirportFrom,AirportTo,AirportFound。
The columns above display ID's from airports. 上方的列显示了机场的ID。 In the table Airports are 2 columns AirportID and AirportName. 在表Airports中有2列AirportID和AirportName。 Instead of displaying the ID's from the airports I want to display the AirportNames. 我不想显示机场的ID,而是要显示AirportNames。
But when I use: 但是当我使用时:
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
It only displays the airport name of the first join in every column. 它仅在每列中显示第一个联接的机场名称。 I want to show the airport name for each of the 3 joins 我想显示3个联接中每个联接的机场名称
Provide multiple aliases for joined table each time you left join, and join them as you have multiple tables: 每次离开联接时,为联接表提供多个别名,并在拥有多个表时联接它们:
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
EDIT: Replace reserved words in table aliases. 编辑:替换表别名中的保留字。 Thanks for the reminder! 感谢您的提醒!
Your query needs table aliases (for multiple joins to the same table). 您的查询需要表别名(对于同一表的多个联接)。 Then, be sure to use qualified columns names for all columns in a query. 然后,请确保对查询中的所有列使用合格的列名称。 This helps you write correct queries and it helps you and other people understand what is going on. 这可以帮助您编写正确的查询,还可以帮助您和其他人了解正在发生的事情。 So: 所以:
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.