2016-06-30 30 views
0

我有以下的架構和查詢其抓住嵌套組的每個項目,並返回一個逗號分隔的祖先名單:MySQL的動態透視從嵌套集合

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; 

小提琴: http://sqlfiddle.com/#!9/0a854/10

結果:

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

我想樞/中單獨數值當家列分隔祖先,像這樣:

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

的祖先可能是從字面上什麼,我不知道什麼或多少會有的方式。

我不知道從哪裏開始,但如果它有幫助,我可以使用準備好的語句,存儲過程,函數..整個shebang。

回答

1

一種方法是將您的查詢放入此中。它會將結果從你的查詢中分割出來:

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; 
+0

這對我有用......它沒有解決未知數量的祖先,而是在過渡期間爲我工作。 – superphonic