我正在使用postgresql。我有2个表,如lt_organization(child)和lt_organizationparent(parent) 两个表都包含父/子关系。 下面是id postgres递归查询。 如果我传递父ID,则应返回该父ID的所有子记录以及大子记录。
CREATE OR REPLACE FUNCTION pc_daimler_qa.sp_transcript_export(IN _integration integer,IN _mode integer,IN _args text)
RETURNS TABLE(sessionfk integer, userfk integer, username citext, firstname citext, lastname citext, coursefk integer, coursename citext, coursecode citext, completiondate timestamp without time zone) AS
$BODY$
DECLARE
_orgid integer default 0;
_orgcode varchar(20);
BEGIN
select split_part(_args,',',1) into _orgcode;
if (_mode = 1) then
select id into _orgid from lt_organization where code = _orgcode and softdelete=0;
RETURN QUERY
WITH RECURSIVE orgslist AS
(
SELECT
op.orgidfk,
op.orgparentidfk
FROM lt_organizationparent op
left join lt_organization oo on oo.id=op.orgidfk
WHERE op.orgparentidfk=_orgid and oo.softdelete=0
UNION ALL
SELECT m.orgidfk, m.orgparentidfk FROM lt_organizationparent m
left join lt_organization o on o.id=m.orgidfk
JOIN orgslist ON orgslist.orgidfk = m.orgparentidfk
where o.softdelete=0
)
,recent_sessions as
(
SELECT DISTINCT ON (c.courseid) s.id as sessionFK,
u.id as userFK,u.username as username,u.firstname,u.lastname,
c.id as courseFK,c.coursename,
c.courseid as coursecode,s.completiondate
FROM tblsession s
left join tbluser u on u.id=s.userid
left join tblcourse c on c.id=s.courseid
left join lb_genmap g on g.id1fk=u.id
left join tblsyscoursestatus t on t.id=s.status
left join lt_organization o on o.id=g.id2fk
left join LT_SysCourseType sct on sct.id = c.typefk
where (t.isComplete=1 and t.isfailed=0)`and (g.typefk=5 and g.isPrimary=1 and g.id2fk in (select orgidfk from orgslist)) //This line take single record.`
and (u.active=1 and u.deleted=0) and (sct.iswbt=1 and sct.isilt=0) and (c.deleted = 0)
ORDER BY c.courseid ASC, s.completiondate DESC
)
select * from recent_sessions r;
end if;
exception when others then
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100
ROWS 1000;
ALTER FUNCTION pc_daimler_qa.sp_transcript_export(integer, integer, text)
OWNER TO postgres;
当我在下面选择语句时触发 SELECT * FROM pc_daimler_qa.sp_transcript_export(5,1,' Org123');
我有单个孩子记录而不是多个记录。
感谢。