CTE récursif pour la relation parent et enfant dans SQL Server

Ok donc j'ai vu beaucoup d'exemples en ligne de ceci mais je ne peux pas l'get pour fonctionner avec ma table.

Table: produit
Colonnes: parent_product_id, child_product_id

Si parent_product_id = child_product_id le parent_product_id n'a pas de parent.

Un child_product_id pourrait être le parent d'un autre logging.

J'ai essayé de le faire mais il me faut une éternité pour voir la hiérarchie de parent_product_id = 392193

 ;with parents as ( select child_product_id, parent_product_id from product where parent_product_id = child_product_id union all select e.child_product_id, e.parent_product_id from product e inner join parents m on e.parent_product_id = m.child_product_id) select * from parents where parents.parent_product_id = 392193 option (maxrecursion 0) 

Quelqu'un peut-il me donner un coup de main?

Vous pouvez déplacer la condition de départ dans le CTE:

 ; with parents as ( select child_product_id , parent_product_id from product where child_product_id = 392193 and parent_product_id = 392193 union all select e.child_product_id , e.parent_product_id from parents m join product e on e.parent_product_id = m.child_product_id ) select * from parents option (maxrecursion 0) 

Un index sur (parent_product_id, child_product_id) aiderait.

Généralement, un logging enfant fait reference à la key primaire de son logging parent. Dans votre cas, il se passe quelque chose d'inhabituel, le parent ayant un "child_product_id". Quelques informations supplémentaires sur cette construction clarifieraient votre question.

essaye ça:

 ;with parents as ( select parent_product_id, child_product_id from product where parent_product_id = child_product_id union all select m.parent_product_id, --this should be parent of top level e.child_product_id from product e inner join parents m on e.parent_product_id = m.child_product_id WHERE e.parent_product_id != e.child_product_id ) select * from parents where parents.parent_product_id = 392193 option (maxrecursion 0)