MySQL 嵌套集的动态枢轴

MySQL Dynamic Pivot From Nested Set

我有以下架构和查询,它获取嵌套集中的每个项目,returns 一个逗号分隔的祖先列表:

CREATE TABLE Tree
(title varchar(20) PRIMARY KEY,
 `tree` int,
 `left` int,
 `right` int);

INSERT Tree
VALUES
("Food", 1, 1, 24),
('Fruit', 1, 2, 13),
('Red', 1, 3, 8),
('Cherry', 1, 4, 7),
('Cherry_pie', 1, 5, 6),
('Yellow', 1, 9, 12),
('Banana', 1, 10, 11),
('Meat', 1, 14, 23),
('Beef', 1, 15, 16),
('Pork', 1, 17, 22),
('Bacon', 1, 18, 21),
('Bacon_Sandwich', 1, 19, 20);

查询

SELECT T0.title node
  ,(SELECT GROUP_CONCAT(T2.title ORDER BY T2.left)
                FROM Tree T2
                WHERE T2.left < T0.left AND T2.right > T0.right
                ) ancestors
FROM Tree T0
GROUP BY T0.title;

Fiddle: http://sqlfiddle.com/#!9/0a854/10

结果:

title          | ancestors
--------------------------
Bacon          | Food,Meat,Pork
Bacon_Sandwich | Food,Meat,Pork,Bacon
Banana         | Food,Fruit,Yellow
etc.....

我想pivot/separate先辈把数字列分开,像这样:

title          | 1    | 2      | 3      | 4    
----------------------------------------------
Bacon          | Food | Meat   | Pork   |
Bacon_Sandwich | Food | Meat   | Pork   | Bacon
Banana         | Food | Fruit  | Yellow |
etc.....

祖先可以是任何东西,我不知道会有多少。

我不知道从哪里开始,但如果有帮助,我可以使用准备好的语句、存储过程、函数......整个 shebang。

一种方法是将您的查询放入其中。它将从您的查询中拆分结果:

SELECT
  d.node
  , REVERSE(SUBSTRING_INDEX(REVERSE (SUBSTRING_INDEX(CONCAT(d.ancestors,',,,,'), ',', 1)),',',1)) AS `1`
  , REVERSE(SUBSTRING_INDEX(REVERSE (SUBSTRING_INDEX(CONCAT(d.ancestors,',,,,'), ',', 2)),',',1)) AS `2`
  , REVERSE(SUBSTRING_INDEX(REVERSE (SUBSTRING_INDEX(CONCAT(d.ancestors,',,,,'), ',', 3)),',',1)) AS `3`
  , REVERSE(SUBSTRING_INDEX(REVERSE (SUBSTRING_INDEX(CONCAT(d.ancestors,',,,,'), ',', 4)),',',1)) AS `4`

FROM (
  SELECT T0.title node
        ,(SELECT GROUP_CONCAT(T2.title ORDER BY T2.left)
                      FROM Tree T2
                      WHERE T2.left < T0.left AND T2.right > T0.right
                      ) ancestors
  FROM Tree T0
  GROUP BY T0.title
) AS d;