MYSQL中动态行数据转列数据
最近用到城市矩阵相关 需要将城市与城市距离转化为二维表 通过动态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;