mysql - (MySQL) MPTT/嵌套集模型上的聚合函数

标签 mysql aggregate-functions nested-sets mptt

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

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

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

目前我正在使用:

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

我真的不知道如何让它在父级“未发布”时忽略“子级”类别。

我还尝试将此链接到我的“new_products”表,该表包含以下字段:product_idnamestockpricecategory_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

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

最佳答案

随着节点深度的增加一点点:

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

关于mysql - (MySQL) MPTT/嵌套集模型上的聚合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5411153/

相关文章:

css - kohana 框架 3.1.2 如何通过 Nested Sets 制作菜单

mysql - 为什么我在 Create Table 的第 1 行收到错误

mysql - 如何在MYSQL中选择与其他表中的多行交集相匹配的行?

mysql - sql:使用单个查询在另一列中选择具有相同列值的行

sql - 如何在 postgresql 中使用 array_agg 包含 NULL 值?

sql - 帮助为嵌套集编写 SQL 查询

mysql - 与 MySql 中的 only_full_group_by 相关的错误

performance - 在多个过滤器上优化聚合查询

sql - 在 MYSQL 查询分组方面需要帮助

php - 将嵌套集模型放入 <ul> 但隐藏 "closed"子树