0

Nested Set モデルを使用してカテゴリに取り組んでいます。私のDB設計はこのようなものです

  • 表 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 列に更新する方法を教えてください。

あなたの助けに感謝。

4

2 に答える 2

0

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;
    

これには列を更新するオーバーヘッドが追加されることはわかっていますが、それには正当な理由があり、他に方法が見つかりませんでした。とにかくあなたの答えに感謝します。

于 2012-12-20T11:35:17.170 に答える
0

このようなものは、カテゴリを参照する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
  )
于 2012-12-19T19:02:42.127 に答える