【问题标题】:SQL query to count number of items in secondary table using Nested Set model使用嵌套集模型计算辅助表中项目数的 SQL 查询
【发布时间】:2012-12-20 19:35:17
【问题描述】:

我正在使用嵌套集模型处理类别。我的数据库设计是这样的

  • 表 1:类别(id、lft、rgt、count1、count2)
  • 表 2:Items1 (id, catid, .....) -- catid 是类别表中的 id
  • 表 3:Items2 (id, item1_id, ....) -- item1_id 是 Items 1 表中的 id

现在由于 Items1 有 catid 列,我可以使用下面的 SQL 使用嵌套集模型轻松计算树下的项目数:

        SELECT 
            parent.id, COUNT(items.id) as item_count
        FROM 
            categories AS node ,
            categories AS parent,
            items1 AS items
        WHERE 
            node.nleft BETWEEN parent.nleft AND parent.nright 
            AND node.id = items.catid
            AND items.published = 1
        GROUP BY 
            parent.id
        ORDER BY 
            node.nleft;

并从该 SQL 更新每个类别。

现在有人可以帮我如何将每个类别的项目数从 items2 表更新到 count2 列吗?

感谢您的帮助。

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    这样的事情会将count2 设置为items2 中引用该类别的行数:

    update 
      categories 
    set 
      count2=(
        select count(*) from items2 where items2.item1_id in (
          select id from items1 where items1.catid=categories.id
        )
      )
    

    要将count2 设置为items1items2 中引用该类别的行数:

    update 
      categories 
    set 
      count2=(
        select count(*) from items2 where items2.item1_id in (
          select id from items1 where items1.catid=categories.id
        ) + 
        select count(*) from items1 where items1.catid=categories.id
      )
    

    【讨论】:

    • 我想我的查询不清楚。我想要的是树下所有类别的总和。例如,考虑类别树路径 A->B->C,A 中的计数应该是 A+B+C 中的计数总和,而 B 中的计数应该是 B+C 的总和。请参阅上面的 SQL,我是如何处理 item1 计数的。我希望我现在清楚了。
    • 我扩展了我的答案,但我猜我实际上并没有理解你的数据模型。 nleftnright 是干什么用的?
    • 是为了方便嵌套集合模型。值在其他节点的 nleft 和 nright 之间的节点是这些节点的子节点,允许具有高可查询性的自引用项树
    • 谢谢@Charleh - 我误解了这个问题
    【解决方案2】:

    感谢 MiMo 的回复。最后,我可以自己做。

    我所做的是,

    1. 在 items1 表中添加了一个新列 item22_count,并在向 items2 表中插入新记录时更新它。

    2. 现在我像这样修改了第一个查询以获得 items2 计数。

      SELECT 
          parent.id, sum(items2_count) as item2_count
      FROM 
          categories AS node ,
          categories AS parent,
          items1 AS items
      WHERE 
          node.nleft BETWEEN parent.nleft AND parent.nright 
          AND node.id = items.catid
          AND items.published = 1
      GROUP BY 
          parent.id
      ORDER BY 
          node.nleft;
      

    我知道这会增加更新列的开销,但这是有充分理由的,我没有找到其他方法。无论如何感谢您的回答。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 2021-11-22
      • 2014-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多