在mysql中进行动态矩阵查询

时间:2016-08-31 06:24:17

标签: mysql matrix dynamic

我想从这些数据中进行矩阵查询

name    distance
roby    10
dina    5
axel    6
john    8

我按照这样的方式进行查询:

SELECT tabel1.name, tabel2.name,tabel1.distance,tabel2.distance  
FROM passenger tabel1 
LEFT JOIN passenger tabel2 ON tabel1.name != tabel2.name AND tabel1.id < tabel2.id  
WHERE tabel2.name IS NOT NULL 
ORDER BY tabel1.name ASC, tabel2.name ASC

结果是这样的:

name    name    distance    distance
axel    john       6           8
dina    axel       5           6
dina    john       5           8
roby    axel       10          6
roby    dina       10          5
roby    john       10          8

但我希望结果是这样的:

       roby    dina    axel    john
roby    0       10      10      10
dina    5       0       6       8
axel    6       5       0       8
john    8       5       6       0

有可能吗?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

SET @sql = NULL;
SELECT
   GROUP_CONCAT(DISTINCT
     CONCAT(
        'IF(a.distance = ''',
            distance,
            ''', 0, a.distance) AS "',
         name,'"'
     )
   ) INTO @sql
FROM your_table;




SET @sql = CONCAT('SELECT a.name,' ,@sql, ' 
               FROM your_table AS a
               LEFT JOIN your_table AS b
                ON a.name=b.name GROUP BY a.name,b.name');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

根据您所需的结果更新查询。 小提琴link