你們在作項目的時候,展現樹形結構的數據,確定遇到須要經過父節點遞歸查詢全部子節點的狀況,node
也應該作過經過子節點查詢全部父級節點的需求。mysql
本次遇到的需求是一次性查詢多個子節點的全部父級節點的狀況。sql
多個節點咱們考慮到要去除重複節點。數據庫
常規作法:mybatis
1. 數據庫中寫一個自定義函數,查詢當前節點的全部父級節點app
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. 後臺屢次傳遞子節點調用當前子節點子查詢全部父級節點。函數
3.單次調用到的結果存到List中。性能
4.屢次調用的結果彙總,去重做爲最終結果。spa
其實還有種最簡單的作法:利用union查詢,結果自動去重code
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
若是達到如上效果,一種在mysql執行動態sql,
還有一種是經過mybatis foreach標籤實現:
Mapper中的方法
/** * 查詢多個部門的全部父級部門(遞歸,數據量大,確定影響性能) * @param deptIds * @return */ List<ZTreeNode> getParentZTeeNodeByDeptIds(@Param("deptIds") String[] deptIds);
Mapper.xml 配置
<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>
這樣能經過一次傳遞多個子節點參數 deptIds = 11,18,完成最終結果查詢。