创建pg数据库zc_tree表字段分别有
id 索引
name 名称
pid 父类id
base_code 编码
实体类
@Data
public class ZcTreeEntity {
private int id;
private String name;
// 父id
private int pid;
// 编码
private String base_code;
// 子类
private List<ZcTreeEntity> list;
}
方法,获取树状结构
public static List<ZcTreeEntity> pushManyGroup(List<ZcTreeEntity> list, int parentId){
List<ZcTreeEntity> indexs = new ArrayList<>();
for(ZcTreeEntity ki:list){
if(parentId == ki.getPid()){
ki.setList(pushManyGroup(list, ki.getId()));
indexs.add(ki);
}
}
return indexs;
}
Sql根据子类的base_code获取各级的父类数据
WITH RECURSIVE cte AS (
SELECT id, name, pid,base_code
FROM zc_tree
WHERE base_code = 'xxxxxxxxx'
UNION ALL
SELECT t.id, t.name, t.pid, t.base_code
FROM zc_tree t
JOIN cte ON t.id = cte.pid
)
SELECT base_code
FROM cte order by id desc;