Search code examples
mysqlsql-order-bynested-sets

Nested Sets: Retrieving Multiple Paths


Is it possible to retrieve multiple paths from MySQL nested sets? Emphasis is on the second line of the where condition.

SELECT parent.name
FROM nested_category AS node,
    nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
    AND node.name = 'Name1' OR node.name = 'Name2'
ORDER BY node.lft;

Solution

  • Yes, of course.

    In SQL, OR has lower precedence than AND, so you need to rewrite the query as:

    SELECT  parent.name
    FROM    nested_category AS node
    JOIN    nested_category AS parent
    ON      node.lft BETWEEN parent.lft AND parent.rgt
    WHERE   node.name IN ('Name1', 'Name2')
    ORDER BY
            node.lft;
    

    This query is quite inefficient in MySQL because the join condition is not sargable.

    You may want to store your sets as LineString and use spatial indexes to speed up the query.

    See this entry in my blogs for details: