子查询的自加入?

时间:2017-04-20 19:22:40

标签: mysql

我有两个数据集,航班延误和机场代码。 航班延迟数据集包括以下列:OriginAirportID和 DestAirportID。

机场代码数据集有4个cols:airport_id,city,state和name。 我编写了以下查询来连接两个数据集:

select OriginAirportID, DestAirportID, name as DestName, city as DestCity, state as DestState
FROM t1 LEFT OUTER JOIN t2
ON t1.[DestAirportID] = t2.[airport_id];

然后,我有一个单一的数据集。但实际上,我正试图获得 originAirportID的airport_id,名称和城市字段也是如此。 然后,我尝试了一个自连接查询来提取数据。

select Origin.DestName AS OriginName, Dest.DestName AS DestName, 
Dest.OriginAirportID, DestAirportID, DestCity, DestState
FROM t1 AS Dest
INNER JOIN t1 AS Origin
ON Origin.OriginAirportID = Dest.DestAirportID;

但实际上,我在每个目的地之间得到了一些组合 到达地点。然后,我使用了一些子查询,但我没有得到预期 结果

select OriginAirportID, DestAirportID, DestName, DestCity
FROM t1 AS DEST01
WHERE DestName = 
  (SELECT DestName FROM t1 AS DEST02
  WHERE DEST01.OriginAirportID = DEST02.OriginAirportID);

0 个答案:

没有答案