with recursive anc as(select * from t_person where id=9999999 UNION select p.* from t_person p join anc on p.id=anc.idm or p.id=anc.idf) select * from anc where idm is NULL xor idf is NULL