最近用到城市矩阵相关 需要将城市与城市距离转化为二维表 通过动态SQL直接实现 贴出来一起学习:

表就三个字段,包含在sql内。

 
SET @sql:='';

SELECT @sql:=GROUP_CONCAT(item) FROM(
SELECT CONCAT(@sql,'SUM(IF(to_city=\'',to_city,'\'',',distance,0)) AS \'',to_city,'\'') item
FROM (SELECT cm.to_city 
FROM `cities_matrix`  cm  GROUP BY cm.to_city ORDER BY cm.to_city)a
)a
;

SET @sql:=CONCAT('SELECT cm.from_city,',@sql,' FROM cities_matrix cm GROUP BY cm.from_city');
 
PREPARE stmt FROM @sql;  
EXECUTE stmt;   

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-13
  • 2021-09-26
  • 2022-12-23
  • 2021-05-01
猜你喜欢
  • 2022-12-23
  • 2021-06-03
  • 2022-02-19
  • 2022-12-23
  • 2022-12-23
  • 2021-12-09
  • 2021-10-24
相关资源
相似解决方案