最近用到城市矩陣相關 須要將城市與城市距離轉化爲二維表 經過動態SQL直接實現 貼出來一塊兒學習: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;