Nested Set Query to retrieve all ancestors of each node

后端 未结 2 1654
执念已碎
执念已碎 2021-02-06 07:44

I have a MySQL query that I thought was working fine to retrieve all the ancestors of each node, starting from the top node, down to its immediate node. However when I added a 5

2条回答
  •  耶瑟儿~
    2021-02-06 08:28

    You can get the result using JOIN or SUB-QUERY.

    Using JOIN:

    SELECT t0.title node, GROUP_CONCAT(t2.title ORDER BY t2.left) ancestors 
    FROM Tree t0
    LEFT JOIN Tree t2 ON t2.left < t0.left AND t2.right > t0.right
    GROUP BY t0.title; 
    

    Check this SQL FIDDLE DEMO

    Using SUB-QUERY:

    SELECT t0.title node, 
          (SELECT GROUP_CONCAT(t2.title ORDER BY t2.left)
           FROM Tree t2 WHERE t2.leftt0.right) ancestors
    FROM Tree t0
    GROUP BY t0.title;
    

    Check this SQL FIDDLE DEMO

    OUTPUT

    |           NODE |             ANCESTORS |
    |----------------|-----------------------|
    |          Bacon |        Food,Meat,Pork |
    | Bacon_Sandwich |  Food,Meat,Pork,Bacon |
    |         Banana |     Food,Fruit,Yellow |
    |           Beef |             Food,Meat |
    |         Cherry |        Food,Fruit,Red |
    |     Cherry_pie | Food,Fruit,Red,Cherry |
    |           Food |                (null) |
    |          Fruit |                  Food |
    |           Meat |                  Food |
    |           Pork |             Food,Meat |
    |            Red |            Food,Fruit |
    |         Yellow |            Food,Fruit |
    

    In your sub query you had used ORDER BY after WHERE clause which won't affect the output. By default GROUP_CONCAT() function will orders the output string in ascending order of column value. It won't consider you explicit ORDER BY clause.

    If you check your output of first query which returns the data in ascending order of title column. So the returned result for node Banana is Food,Fruit,Yellow.

    But in your second result for Bacon_Sandwich is Bacon,Food,Meat,Pork because in ascending order Bacon comes first than Food will come.

    If you want to order the result based on left column than you have to specify ORDER BY inside the GROUP_CONCAT() function as above. Check my both queries.

    I prefer that you use JOIN instead of SUB-QUERY for improving performance.

提交回复
热议问题