Mysql的层级递归关联的数据,实现根据子id查询全部父级信息,根据父id查询全部子级信息

一:根据父id查询全部子级信息

  SELECT
            id
        FROM
            (SELECT
                t1.id,
                IF(FIND_IN_SET(parent_id, @parentId) > 0, @parentId:=CONCAT(@parentId, ',', id), 0) AS ischild
            FROM
                (SELECT
                id, parent_id
            FROM
                security_organization t
            WHERE
                valid = 1
            ORDER BY parent_id , id) t1, (SELECT @parentId:=#{parentId}) t2) t3
        WHERE
            ischild != 0

二:根据子id查询全部父级信息

 SELECT
    @r AS org_id,
    ( SELECT @r := parent_id FROM security_organization WHERE id = org_id ) AS parent_id,
    @l := @l + 1 AS lvl,
    h.docking_phone,h.docking_mail
    FROM
    ( SELECT @r := #{childId}, @l := 0 ) vars,
    security_organization h
    WHERE
    @r != 0
    AND parent_id > 0

posted @ 2022-08-11 18:49  码海兴辰  阅读(16)  评论(0编辑  收藏  举报