SQL - 依赖递归类别

时间:2013-09-23 08:15:15

标签: sql recursion count group-by categories

我陷入了计数查询。

我有3张桌子:

Articoli
ID | Title | ecc...

Categories
ID | Name | Parent

articles_category
category_id | article_id

类别是递归的,例如我有一个主要类别“新闻”,有3个子猫。

我需要计算“新闻”中有多少文章,但我的文章在“articles_category”表中标记了subcat ID(如果有SubCat)或主Cat ID,如果它没有subcat。到目前为止我试过了:

SELECT count(a.id), child.name AS child, parent.name AS parent
FROM categories parent
JOIN categories child ON child.parent = parent.tid
JOIN categories_articoli ca ON child.tid = ca.category_id
   OR parent.tid = ca.category_id
JOIN articoli a ON a.id = ca.articolo_id
GROUP BY parent.tid

但是这只返回了有子类别的父猫,但这是每次都是真的。有什么建议吗?

3 个答案:

答案 0 :(得分:1)

您需要在Categories表上使用recursive sql

试试这个:

新闻类别中文章的数量(*):

with category_tree(id) as
 (select  c.id
    from Categories c
   where c.name='News'--category tree starting with 'News'
  union all
  select  c.id
    from category_tree ct
   inner join Categories c
      on c.parent = ct.id)
select  count(distinct ac.article_id) from category_tree ct
inner join articles_category ac on ac.category_id = ct.id

按类别计算文章(*):

with category_tree(id, root_category_name) as
 (select c.id,  c.name
    from Categories c
   where c.parent is null
  union all
  select  c.id,  ct.root_category_name
    from category_tree ct
   inner join Categories c
      on c.parent = ct.id)
select ct.root_category_name, count(distinct ac.article_id) from category_tree ct
inner join articles_category ac on ac.category_id = ct.id
group by ct.root_category_name

http://sqlfiddle.com/#!4/d42aa/12

答案 1 :(得分:0)

非常感谢!

运气不好我不能在mysql中使用“WITH”语句(抱歉我没有指定),但我用这种方式解决了我的问题:

  • 创建一个数据集,每个ID与其parent_category名称相关联
  • 将其加入categories_articoli表
  • 按parent_category名称分组。

以下是有人可能需要这样的问题:

SELECT count(distinct ca.articolo_id), cat.name 
FROM categories_articoli ca
JOIN(
    SELECT c.tid AS ID, c.name AS name, c.parent
    FROM categories c
    WHERE c.parent = 0 AND c.tid <> 6
    UNION
    SELECT c.tid AS ID, parent.name AS name, c.parent
    FROM categories c
    JOIN categories parent ON c.parent = parent.tid
    WHERE c.parent <> 0 AND c.tid <> 10
) cat
ON cat.ID = ca.category_id
GROUP BY cat.name

答案 2 :(得分:-2)

我认为这是错误的,因为你的解决方案不要写&#34; top&#34;类别(fe。:你的猫3号在2合1中,而物品只在3类中 - 你的解决方案将返回3类和2类物品的正确数量,但类别1不会在结果中,它应该在那里)