2016-05-27 103 views
0

我有以下表格:MYSQL:由兩個外鍵從同一個表中選擇

航班: ID,idcompany,idplane,fromCity,toCity,起飛......

公司: 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的名字,所以我能做些什麼用相同的查詢,以獲得兩個名字?

+0

添加一些示例表數據,目前的結果和預期的結果。 – jarlh

回答

2

您可以使用此:

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從現在開始。

+0

三個答案都是權利,現在哪一個具有最高的性能? – Mohammad

+2

@Mhamhammad,相同的性能,只有不同的語法版本。 – jarlh

1

你必須加入表格兩次。

SELECT f.id, f.takeoff, f.arrival, ct.name as fromCity, f.toCity, c.name as company, p.name as plane , cf.name 
FROM flights f, companies c, planes p, cities ct,cities cf 
WHERE f.idCompany = c.id AND f.idPlane = p.id AND f.fromCity = ct.id AND f.toCity = cf.id 
ORDER BY f.takeoff ASC 
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 
+0

幾乎與Pham X.巴赫的答案一樣,但仍然與舊式,隱式聯接... – jarlh

+1

@jarlh是啊對,所以我會接受Pham X.巴赫的答案 – Mohammad