sql 递归查询 孩子节点数据

# sql 递归查询 孩子节点数据


-- 向上查询(查询所有父亲节点,包含自己)
WITH RECURSIVE res AS (
    SELECT t1.* FROM gaia_ocm_area AS t1
    --WHERE t1.id = '当前节点'
    UNION
    SELECT t2.* FROM gaia_ocm_area AS t2
    INNER JOIN res AS t3 ON t2.id = t3.parent_id  
    WHERE 1=1
)
SELECT res.* FROM res

-- 向下查询(查询所有孩子节点,包含自己)
WITH RECURSIVE res AS (
    SELECT t1.* FROM gaia_ocm_area AS t1  
    --WHERE t1.id = '当前节点'
    UNION 
    SELECT t2.* FROM gaia_ocm_area AS t2
    INNER JOIN res AS t3 ON t3.id = t2.parent_id
    WHERE 1=1
)
SELECT res.* from res

-- 向下查询(查询所有儿子节点,不包含自己) -->
WITH RECURSIVE res AS (
    SELECT t1.* FROM gaia_ocm_area AS t1
    WHERE t1.parent_id = #{
     currentNodeId}
    UNION
    SELECT t2.* FROM gaia_ocm_area AS t2
    INNER JOIN res AS t3 ON t3.id = t2.parent_id
)
SELECT res.* from res

你可能感兴趣的:(sql,空间算法函数,postgresql,sql)