0

データベースにテーブルがありますtype

ID  Name     ParentID
---------------------
1   name1    0
2   name2    0
3   name3    1
4   name4    2
5   name1    1

各タイプの親 (子孫) の数を知る必要があります

ID -------- 子孫

ID-> 1   (have no parent)
ID-> 3   (have 1 parent (ID->1))
ID-> 5   (have two parent ((ID->3(ID->1))))

MySQL を使用してこれを行うために最適化された SQL ステートメントを作成するにはどうすればよいですか?

4

2 に答える 2

0


また、次のレベルの並べ替えを計算する関数を実装することもできます。

create function get_level(_id int) returns int
begin
  declare _level int default -1;
  repeat
    set _level = _level + 1;

    select parent_id
    into _id
    from your_table
    where id = _id; 
  until _id is null
  end repeat;
  return _level;  
end

使用法:

select id, get_level(id)  
from your_table  

私はコードをテストしません。そのアプローチは効果的ではありません。ほとんどの場合、挿入/更新時にレベルを保存して計算することをお勧めします。

于 2010-02-07T19:10:25.157 に答える
0

残念ながら、MySQL は再帰的な CTE をサポートしていません。ただし、親の数が限られている場合は、結合を使用してこれを実装できます。

select p.id
,      case 
           <... more whens here ...>
           when c3.id is not null then 3
           when c2.id is not null then 2
           when c1.id is not null then 1
           else 0
       end as NumberOfChildren
from yourtable p
left join yourtable c1 on c1.parentid = p.id
left join yourtable c2 on c2.parentid = c1.id
left join yourtable c3 on c3.parentid = c2.id
<... more joins here ...>
group by p.id
于 2010-02-07T18:24:02.050 に答える