I found it more easily to :
1) create a function that will check if a item is anywhere in the parent hierarchy of another one. Something like this (I will not write the function, make it with WHILE DO) :
is_related(id, parent_id);
in your example
is_related(21, 19) == 1;
is_related(20, 19) == 1;
is_related(21, 18) == 0;
2) use a sub-select , something like this:
select ...
from table t
join table pt on pt.id in (select i.id from table i where is_related(t.id,i.id));