All at once the parent node query multiple child nodes

Everyone in doing the project, show the data of the tree structure, certainly encountered the situation requires all child nodes of a recursive query through the parent node,

Queries should be done for all the needs of the parent node through child nodes.

The requirement is met if all the parent node's one-time query multiple child nodes.

We take into account the multiple nodes to remove duplicate nodes.

General practice:

1. Database write a custom function to query the current node's parent node for all

DROP FUNCTION if EXISTS fn_getParentNodes;
CREATE FUNCTION fn_getParentNodes(currentId VARCHAR(64))
RETURNS VARCHAR(1000)
BEGIN
    DECLARE parentId VARCHAR(100);
    DECLARE tempStr VARCHAR(1000) DEFAULT currentId;
    WHILE currentId is not null DO
      SET parentId = (SELECT pid FROM dept WHERE id = currentId );
        IF parentId is not null THEN
            set tempStr = CONCAT(parentId,',',tempStr);
            set currentId = parentId;
    ELSE 
            set currentId = parentId;
        END IF;
    END WHILE;
RETURN tempStr;
END;
SELECT id,pid,name from dept where FIND_IN_SET(id, fn_getParentNodes('11'))

2. Background repeatedly delivered the child node called the current child node sub-queries all of its parent node.

3. single call to save the results to a List.

4. A summary of the results of multiple calls, go heavy as the final result.

 

In fact, there are kinds of easiest way: the use of union query, results are automatically de-emphasis

SELECT id,pid,name from dept where FIND_IN_SET(id, fn_getParentNodes('11'))
UNION
SELECT id,pid,name from dept where FIND_IN_SET(id, fn_getParentNodes('18'))
ORDER BY pid

If achieve the above effect, in a method of performing dynamic sql mysql,

There is also a realization by mybatis foreach Tags:

Mapper Methods

    / ** 
     * Query all departments of the parent department (recursion, the amount of data, certainly affect performance) 
     * @param deptIds 
     * @return 
     * / 
    List <ZTreeNode> getParentZTeeNodeByDeptIds (@Param ( "deptIds") String [] deptIds );

Mapper.xml Configuration

    <select id="getParentZTreeNodeByDeptIds" resultType="com.core.node.ZTreeNode">
        <foreach collection="deptIds" index="index" item="i"  separator="UNION" >
            SELECT
            id,pid,name
            FROM dept
            WHERE FIND_IN_SET(id, fn_getParentNodes(#{i}))
        </foreach>
        ORDER BY pid;
    </select>

Thus by transmitting a plurality of child nodes parameters deptIds = 11,18, the final result of the query is completed.

 

Guess you like

Origin www.cnblogs.com/liuxiutianxia/p/11240620.html