报表1-创建sql函数get_children_all
为了报表的统计,创建一个取实体所有下级的函数,名为get_children_all,传递实体代码和最大层级两个参数。
CREATE OR REPLACE FUNCTION get_children_all(entity_id UUID, max_level INT DEFAULT 6)
RETURNS TABLE(entity_child_id UUID, entity_child_type CHARACTER VARYING, entity_level INT, relation_type CHARACTER VARYING) AS $$
BEGINRETURN QUERYWITH RECURSIVE entity_tree AS (-- 基础查询:直接下级(所有关系类型)SELECT r.to_id as child_id,r.to_type as child_type,r.relation_type as rel_type,1 as levelFROM relation rWHERE r.from_id = entity_idUNION ALL-- 递归查询:继续查找下级(所有关系类型)SELECT r.to_id as child_id,r.to_type as child_type,r.relation_type as rel_type,et.level + 1 as levelFROM relation rINNER JOIN entity_tree et ON et.child_id = r.from_idWHERE et.level < max_level -- 使用传入的层级参数)SELECT DISTINCT child_id, child_type, level, rel_typeFROM entity_tree;
END;
$$ LANGUAGE plpgsql;
输入如下语句查询
select * From get_children_all('5fd7e540-67a3-11f0-a3ef-fd437db78ef1')