I work with postgresql version 11
I want to display the unit and it’s children
I try to use recursive query .
this is an example :
unit :
id parentid
UN-25
UN-30 UN-25
UN-31 UN-25
UN-40 UN-30
UN-41 UN-30
UN-255 UN-10
UN-85 UN-10
I want to display UN-25
and it’s children (UN-25 , UN-30 ,UN-31 ,UN-40 , UN-41
)
I try to use this query :
select id from unit where id in (
select distinct id
from
(WITH RECURSIVE tree
AS
(
SELECT
ul.name as node_name, unit.id, unit.parentid as parent_id,
cast(unit.id AS text) AS path,unit.status as status,unit.active as active
FROM unit
left outer join unitlang ul on ul.unit_id=unit.id and ul.lang = 'EN'
WHERE unit.parentid IS NULL
and unit.status='1'
UNION
SELECT
node_name, f1.id, f1.parentid,cast(tree.path || ',' || f1.id AS text) AS path,f1.status as status,f1.active as active
FROM
tree
JOIN unit f1 ON f1.parentid = tree.id
where f1.status='1'
)
SELECT id, node_name, parent_id, node_name, path FROM tree ORDER BY path) liste
where position('UN-25' in path)<>0 and POSITION(id in path)>=POSITION('UN-25' in path)
)
but the problem that this query display :
UN-25 , UN-30 ,UN-31 ,UN-40 , UN-41 , UN-255
the wrong result is related to this id: UN-255
and it was displayed because UN-255
contain UN-25