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

不幸的是,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 回答
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 回答