我有一张这样的表
- 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 :(得分: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
然后,您只需将上述查询的结果插入另一个表中即可。 基本上它的作用是将城市列表与自身联系起来,产生每一对可能的城市,然后使用原始表格计算距离。