2016-11-01 77 views
-2

MySQL的插入值,我有這樣的與操作

- city1 city2 distance 
- BAL BOS 200 
- BAL HKG 8406 
- DET BAL 408 
- BAL LOS 2329 
- ATL BAL 576 

一個表,現在我需要填充一個新表採取任何兩個城市之間的距離是通過BAL

加距離爲例如從DET到HKG = 408 + 8406 = 8814 和羣體需要成對('DET','HKG',8814)以及('HKG','DET',8814)

不知道如何實現這個查詢。謝謝!

+0

有多少站可以有2個城市之間?只有一個(BAL)? – Shadow

回答

0

我不知道,如果它完全在MySQL,但我在SQL Server嘗試這樣做,它的工作原理。該表名爲Distance。

select distinct cities1.city as city1, cities2.city as city2 
, (select top 1 distance from Distance where cities1.city = city1 or cities1.city = city2) 
+ (select top 1 distance from Distance where cities2.city = city2 or cities2.city = city1) as distance 
from 
(select city1 as city from Distance 
union select city2 as city from Distance) as cities1 
join 
(select city1 as city from Distance 
union select city2 as city from Distance) as cities2 
on cities1.city <> cities2.city 

然後,您可以將上面的查詢結果插入到另一個表中。 基本上它是加入與自己的城市名單,導致每一個可能對城市的什麼,然後用原來的表計算距離。

0

你可以試試這個。

這裏你「DET」是你的起始城市, 「HKG」是你的目的地城市

SELECT 
    ctc2.city1, 
    ctc1.city2, 
    ctc1.distance, 
    ctc2.distance, 
    (ctc1.distance+ctc2.distance) AS total_distance 
FROM 
    city_to_city ctc1 
LEFT JOIN ( 
    SELECT 
     city1, 
     city2, 
     distance 
    FROM 
     city_to_city 
    WHERE 
     city1='DET' 
) ctc2 ON (city2=ctc1.city1 AND ctc2.city2= ctc1.city1) 
WHERE 
    ctc1.city2='HKG' 
    AND ctc1.city1='BAL'