/*select schema*/ use genealogy; /*recursive cte1*/ with recursive anc1 as(select *,0000001 st from t_person where id=1673247 UNION select p.*,((2*anc1.st)+(p.Sexe='F')) st from t_person p join anc1 on anc1.idf=p.id or anc1.idm=p.id), /*recursive cte2*/ anc2 as(select *,0000001 st from t_person where id=1673246 UNION select p.*,((2*anc2.st)+(p.Sexe='F')) st from t_person p join anc2 on anc2.idf=p.id or anc2.idm=p.id), /*find intersection between cte1 and cte2*/ ancm as(select anc1.*,least(anc1.st,anc2.st) lst from anc1 join anc2 using(id)), /*colapse double entries with smallest stradonits*/ ancf as(select id,idm,idf,Prenom,Nom,Sexe,min(lst) mst from ancm group by id,idm,idf,Prenom,Nom,Sexe) /*acutual selection of result*/ select *,strad(mst) strad from ancf;