查询以连接两个表

时间:2011-07-26 02:30:06

标签: mysql join

我是MYSQL的新手。任何有关这方面的帮助将不胜感激。

我有两张表机场和帖子,包含以下字段:

机场

id, Airport-code, Airport_name

帖子

id, Source_Airport_code, Destination_airport_code, Date_of_departure, preference

如何获取包含以下字段的记录(此处Source和Destination对应于机场名称而不是代码):

Source, destination, date_of_departure

2 个答案:

答案 0 :(得分:2)

如果Posts.*_Airport_code中的FK未引用Airports.id为MJB假定,而是Airports.Airport_code,那么

SELECT
  APS.Airport_name AS Source,
  APD.Airport_name AS Destination,
  Posts.date_of_departure
FROM Posts
  INNER JOIN Airports APS ON(APS.Airport_code = Posts.Source_Airport_code)
  INNER JOIN Airports APD ON(APD.Airport_code = Posts.Destination_airport_code)

答案 1 :(得分:0)

尝试此操作:

select 
  s.airport_name as source, 
  d.airport_name as destination, 
  p.date_of_departure
from posts p
  inner join airports s
    on p.source_airport_code = s.id
  inner join airports d
    on d.source_airport_code = d.id

我不想这么说,但我认为你还有很长的路要走。