如何在递归 SQL 查询中查找完整节点

How to find a full node in a recursive SQL query

如果产品 table 具有匹配的类别,我想从现有的递归类别树中获取完整节点。

我有以下内容。

WITH ret AS (
        SELECT  ID, ParentID, ProductCategoryId, ProductCategoryName
        FROM    ProductCategoryTree as p1, Products as p2 
        WHERE   p1.ProductCategoryId = p2.ProductCategoryId
        UNION ALL
        SELECT  p.ID, p.ParentID, p.ProductCategoryId, p.ProductCategoryName
        FROM    ProductCategoryTree as p INNER JOIN
                ret r ON p.ParentID = r.ID
      )
SELECT DISTINCT ID, ParentID, ProductCategoryId, ProductCategoryName
FROM ret;

这会给我产品的类别和该类别的所有子节点,但我还需要从上层获取类别(或多个类别)。

如有任何帮助,我们将不胜感激!

正如我们在评论中讨论的那样,您只需在连接的最后一行反转父子关系,它就会起作用:

ret r ON p.ParentID = r.ID