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 名に関連付けられているデータセットを作成します
  • category_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。:猫番号3 in 2 in 1とカテゴリ3のみのアイテムがあります-ソリューションはカテゴリ3と2のアイテムの正しい数を返します、ただし、カテゴリ 1 は結果に含まれず、そこにあるはずです)

于 2015-06-29T19:35:13.677 に答える