加入一个表,其中两列是其他表中的id

时间:2015-05-19 11:35:28

标签: mysql

首先,任何提高我的问题标题的建议都非常受欢迎。这是我的解释。

我有两张桌子。一个是航班,另一个是机场。

flights
-------------------------------------------------------------------
id | departure_id | destination_id | departure_date | arrival_date
-------------------------------------------------------------------
1  |1             | 5              | 2014-05-01     | 2014-05-01
-------------------------------------------------------------------

airports
-----------------------------------
id | country_id | name | timezone |
-----------------------------------
1  | 1          | TPE  | +08:00   |
-----------------------------------
5  | 2          | HND  | +09:00   |
----------------------------------- 

我需要这个结果:

-----------------------------------------------------------
departure_date | departure_tz | arrival_date | arrival_tz |
-----------------------------------------------------------
2014-05-01     | +08:00       | 2014-05-01   | +09:00   |
-----------------------------------------------------------

我有这个查询,但是没有给我我想要的结果,因为我不知道如何建立destination_id,departure_id与表aiports之间的关系,它们都是机场表中的id,请提出任何建议。这是我的查询,但没有区分时区,这是我想要显示的信息。

SELECT flights.flight_number,
  flights.departure_date,
  airports.timezone as departure_tz,
  flights.arrival_date,
  airports.timezone as arrival_tz
FROM flights
JOIN airports

3 个答案:

答案 0 :(得分:1)

window.open("../RegularExpressionTest", '', 'height=500,width=600,left=-150,top=10,status=no,toolbar=no,resizable=yes,scrollbars=yes');

SELECT flights.flight_number, flights.departure_date, A1.timezone as departure_tz, flights.arrival_date, A2.timezone as arrival_tz FROM (flights JOIN airports as A1 ON flights.departure_id=A1.id) JOIN airports as A2 on flights.departure_id=A2.id 从您的查询中丢失,并且您想要从机场加入两个单独的行,您需要使用该表的两个实例。

答案 1 :(得分:1)

SELECT flights.flight_number,
  flights.departure_date,
  dep.timezone as departure_tz,
  flights.arrival_date,
  arvl.timezone as arrival_tz
FROM flights
LEFT JOIN airports dep
ON flights.departure_id = dep.id
LEFT JOIN airports arvl
ON flights.destination_id = arvl.id

答案 2 :(得分:0)

也许2个加入?

SELECT 
t1.id AS flight_number 
t1.departure_date,
t2.timezone AS departure_tz 
t1.arrival_date
t3.timezone AS arrival_tz
FROM flights t1
LEFT JOIN airports t2
ON t1.departure_id = t2.id
LEFT JOIN airports t3
ON t1.arrival_id = t3.id