0

我陷入了计数查询。

我有 3 张桌子:

Articoli
ID | Title | ecc...

Categories
ID | Name | Parent

articles_category
category_id | article_id

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

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

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

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

4

3 回答 3

1

您需要在 Categories 表上使用递归 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

于 2013-09-23T09:57:09.357 回答
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
于 2013-09-23T13:59:45.413 回答
-2

我认为这是错误的,因为您的解决方案没有写“顶级”类别(fe.:您有 2 合 1 中的猫号 3 和仅类别 3 中的项目 - 您的解决方案将返回类别 3 和 2 中项目的正确计数,但类别 1 不会出现在结果中,它应该在那里)

于 2015-06-29T19:35:13.677 回答