sql查询所有父节点 和 所有子节点

查询所有父节点

SELECT id
    FROM ( 
        SELECT 
                @r AS _id, 
                (SELECT @r := direct_recommender FROM t_admin WHERE id = _id) AS parent_id, 
                 @l := @l + 1 AS lvl 
        FROM 
                (SELECT @r := #{要查询的节点id}, @l := 0) vars, 
                t_admin h 
        WHERE @r <> 0) T1 
    JOIN t_admin T2 
    ON T1._id = T2.id
ORDER BY id;

其中 direct_recommender 为表中字段,标示父节点id的字段,t_admin为表名

查询所有子节点

SELECT 
    id
FROM
    (SELECT 
        t1.id,
        IF(FIND_IN_SET(direct_recommender, @pids) > 0, @pids:=CONCAT(@pids, ',', id), 0) AS ischild
    FROM
        (SELECT 
        id, direct_recommender
    FROM
        t_admin t
    ORDER BY id) t1, (SELECT @pids:=#{要查询的节点id}) t2) t3
WHERE
    ischild != 0;   

其中 direct_recommender 为表中字段,标示父节点id的字段,t_admin为表名

上述调用上述两个语句就能获得节点所在树上的所有节点id

转载于:https://my.oschina.net/aidelingyu/blog/3059102

你可能感兴趣的:(sql查询所有父节点 和 所有子节点)