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。
這對我有用......它沒有解決未知數量的祖先,而是在過渡期間爲我工作。 – superphonic