MYSQL:从同一个表中选择两个外键

时间:2016-05-27 11:49:12

标签: mysql sql

我有以下表格:

航班: id,idcompany,idplane,fromCity,toCity,takeoff ...

公司: ID,姓名

飞机: ID,名称

城市: ID,名称

我想宣布两个城市的名字" fromCity,toCity"在同一个查询中。

此操作的目的是立即获取城市名称,因此我可以将其显示给客户端,而无需再进行其他查询来获取城市名称。

这是我的尝试:

SELECT f.id, f.takeoff, f.arrival, ct.name as fromCity, f.toCity, c.name as company, p.name as plane 
FROM flights f, companies c, planes p, cities ct 
WHERE f.idCompany = c.id AND f.idPlane = p.id AND f.fromCity = ct.id 
ORDER BY f.takeoff ASC

此查询将返回" fromCity"的名称。但是" toCity"的id,那么我可以做些什么来通过相同的查询获得这两个名字呢?

3 个答案:

答案 0 :(得分:3)

你可以用这个:

SELECT 
    f.id, f.takeoff, f.arrival, ct1.name as fromCity
    ,ct2.name as toCity, c.name as company, p.name as plane 
FROM 
    flights f
inner join
    companies c
on
    f.idCompany = c.id 
inner join
    planes p
on
    f.idPlane = p.id
inner join
    cities ct1 
on
    f.fromCity = ct1.id 
inner join
    cities ct2
on
    f.toCity = ct2.id   
ORDER BY 
    f.takeoff ASC;

从现在开始尝试不使用 old-style-join

答案 1 :(得分:1)

你必须加入桌子两次。

@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
public class Claim implements Serializable {}

@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
public class Orders implements Serializable {}

答案 2 :(得分:0)

我的解决方案是制作两个表城市的副本:

SELECT f.id, f.takeoff, f.arrival, ct1.name as fromCity, ct2.name as toCity, c.name as company, p.name as plane 

FROM flights f, companies c, planes p, cities ct1, cities ct2 

WHERE f.idCompany = c.id AND f.idPlane = p.id AND f.fromCity = ct1.id AND ct2.id = f.toCity 

ORDER BY f.takeoff ASC