【问题标题】:Hierarchical Product Count using Nested Sets in MySQL在 MySQL 中使用嵌套集的分层产品计数
【发布时间】:2012-10-08 10:43:21
【问题描述】:

如果我有一个嵌套的类别集,如下所示:

Widgets
  Blue
  Red
  Green

我使用关系表将产品引用到这些类别,例如

产品:

id    name
1     Glowing Widget
2     Flying Widget
3     Exploding Widet

关系表:

id    productId    categoryId
1     1            2
2     2            3
3     3            4

有没有什么方法可以创建一个查询来判断一个类别及其子类别引用了多少产品?

【问题讨论】:

  • 您的意思是像在单个查询中使用COUNT()INNER JOIN

标签: mysql nested-sets


【解决方案1】:
SELECT COUNT(DISTINCT productId)
FROM categories
JOIN products_to_categories USING (categoryId)
JOIN products USING (productId)
WHERE categories.left >= {left value of category in question}
AND categories.right <= {right value of category in question}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    相关资源
    最近更新 更多