sql查询树就像结构一样

bog*_*diu 1 sql tree join sql-server-2005

我有一个树类结构的类,树中的树节点有产品,产品有Cods我需要选择所有顶级类别(parent = null),叶子(Cods)匹配一些标准...

SELECT  
    Category.Id AS Id0_, 
    Category.Name AS Name0_, 
    Category.COrder AS COrder0_, 
    Category.Description AS Descript4_0_, 
    Category.ParentId AS ParentId0_, 
    Category.Description_En AS Descript6_0_, 
    Category.Name_En AS Name_En0_, 
    Category.ImagePath AS ImagePath0_ 
FROM
    Category 
    LEFT JOIN Category AS c1 ON Category.Id=c1.ParentId
    LEFT JOIN Category AS c2 ON c1.Id=c2.ParentId
    LEFT JOIN Category AS c3 ON c2.Id=c3.ParentId
    LEFT JOIN Category AS c4 ON c3.Id=c4.ParentId
    LEFT JOIN Product ON 
        c4.Id=Product.Category 
        OR c3.Id=Product.Category 
        OR c2.Id=Product.Category 
        OR c1.Id=Product.Category 
        OR Category.Id=Product.Category
    INNER JOIN Cod ON Cod.Product=Product.Id   
WHERE
    Category.ParentId is null 
    AND Cod.Hidden!='1' 
    AND 
    (
        cod.Stock>0 
        OR (cod.CodBare='0' AND Product.ProdType=8)) 
        AND Cod.Price>0
    )
ORDER BY Category.COrder
Run Code Online (Sandbox Code Playgroud)

我的查询看起来像这样,但它不是一个解决方案,因为它非常慢......有人可以给我一个如何做到这一点的建议吗?

DA.*_*DA. 5

这是一个共同的挑战.从关系数据库创建分层数据并不总是很优雅.如果不经常更新此数据,则可以选择将其作为XML进行吐出,并将其缓存到应用程序中.

如果要将其保留在DB中,这是一种常见的解决方案:在MySQL中管理分层数据.