Is there a simple way to query the children of a node?

前端 未结 6 1027
余生分开走
余生分开走 2020-12-10 05:19

I\'ve been using the crap out of the Nested Set Model lately. I have enjoyed designing queries for just about every useful operation and view. One thing I\'m stuck on is how

6条回答
  •  無奈伤痛
    2020-12-10 06:13

    It seems to me this should be easily doable without the subqueries or parent column redundancy! For example, given parent's left and right are already known:

    SELECT child.id
    FROM nodes AS child
    LEFT JOIN nodes AS ancestor ON
        ancestor.left BETWEEN @parentleft+1 AND @parentright-1 AND
        child.left BETWEEN ancestor.left+1 AND ancestor.right-1
    WHERE
        child.left BETWEEN @parentleft+1 AND @parentright-1 AND
        ancestor.id IS NULL
    

    That is, “from all descendents of the node in question, pick ones with no ancestor between themselves and the node”.

提交回复
热议问题