1

因此,我使用 MySQL 并将我的类别结构存储在基于嵌套集/修改的预排序树遍历模型的表名“nested_category”中,该表具有以下字段: category_id, name, lft, rgt,published

published是 1 或 0...如果是 1,那么该类别将显示在实时站点上。如果为 0,则不会显示在实时站点上,更重要的是,该未发布类别的任何子项也不会显示在实时站点上。

我在编写查询以列出所有具有 的类别published=1并忽略作为具有 的类别的后代的所有类别时遇到问题published=0

目前我正在使用:

SELECT category_id, lft, rgt FROM nested_category WHERE published = 1

当父母“未发布”时,我真的无法弄清楚如何让它忽略“子”类别。

我还试图将其链接到我的“new_products”表,该表具有以下字段:product_id, name, stock, price, category_id,以便我可以编写一个查询来选择所有具有published=1“已发布”类别的产品。我已经做到了这一点:

select @myRight := rgt, @myLeft := lft 
from nested_category where name="ELECTRONICS";

select productId, productName, new_products.category_id, 
price, stock, new_products.published 
from new_products 
inner join ( 
    select category_id, lft, rgt from nested_category 
    where published = 1
) cat 
on new_products.category_id = cat.category_id 
and cat.lft >= @myLeft 
and cat.rgt <= @myRight 
and new_products.published = 1 
order by productName asc

由于上面的查询使用我的第一个查询,它不会返回任何“未发布”类别或产品,但它没有考虑“已发布”类别是“未发布”类别的后代。希望这是有道理的!

4

2 回答 2

1

节点深度略有改善:

SELECT node.name, node.category_id, node.lft, node.rgt, (COUNT(parent.name) - 1) AS depth
FROM nested_category as node
LEFT JOIN (
    SELECT nested_category.category_id, nested_category.lft, nested_category.rgt 
    FROM nested_category, (
        SELECT category_id, lft, rgt 
        FROM nested_category 
        WHERE published = 0
    ) notNodeCat 
    WHERE nested_category.lft >= notNodeCat.lft 
    AND nested_category.rgt <= notNodeCat.rgt ) notNodeCat2
ON notNodeCat2.category_id=node.category_id,
nested_category as parent
LEFT JOIN (
    SELECT nested_category.category_id, nested_category.lft, nested_category.rgt 
    FROM nested_category, (
        SELECT category_id, lft, rgt 
        FROM nested_category 
        WHERE published = 0
    ) notParentCat 
    WHERE nested_category.lft >= notParentCat.lft 
    AND nested_category.rgt <= notParentCat.rgt ) notParentCat2
ON notParentCat2.category_id=parent.category_id            
WHERE notNodeCat2.category_id IS NULL AND notParentCat2.category_id IS NULL AND node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY node.name
ORDER BY node.lft ASC
于 2011-04-28T13:26:11.577 回答
0

好的,所以在玩了很多之后,我已经破解了一些正在工作的东西......

SELECT nested_category.name, nested_category.category_id, nested_category.lft, nested_category.rgt 
FROM nested_category 
LEFT JOIN (
    SELECT nested_category.category_id, nested_category.lft, nested_category.rgt 
    FROM nested_category, (
        SELECT category_id, lft, rgt 
        FROM nested_category 
        WHERE published = 0
    ) notCat 
    WHERE nested_category.lft >= notCat.lft 
    AND nested_category.rgt <= notCat.rgt ) notCat2
ON notCat2.category_id=nested_category.category_id 
WHERE notCat2.category_id IS NULL
ORDER BY nested_category.lft ASC

它显示所有nested_category 项目,其中有一个published=1未被父对象阻止的published=0

我确实需要帮助的一件事是使用更多左连接重写它,因为我听说它们更有效!

于 2011-03-23T22:30:01.847 回答