在MySQL中展平树?

时间:2015-09-11 13:07:12

标签: mysql sql

我有一张名为Ancestry的表,它由两列组成:Parent和Child。我想使用sql创建一个View或extract表,它表示两列中的lineage:Parent和Dependent。 Dependent将是一个孩子,孙子,曾孙子等。 例如,Ancestry表包含以下内容:

Parent   Child
A  ------ A.1
A  ------ A.2
A.1 ----- A.1.1
A.1 ----- A.1.2
A.2 ----- A.2.1
A.2 ----- A.2.2  and so on

注意这些值纯粹是为了说明血统;实际值,孩子数量和树木深度是完全灵活的,我无法控制它们。

我希望我的结果查询生成:

  Parent    Dependent
   null ---- A      (this row may not be possible!)
   A ------- A.1
   A ------- A.2
   A ------- A.1.1
   A ------- A.1.2
   A ------- A.2.1
   A ------- A.2.2
   A.1 ----- A.1.1
   A.1 ----- A.1.2
   A.2 ----- A.2.1
   A.2 ----- A.2.2

当我使用以下内容时,我也会得到兄弟姐妹,而不仅仅是直接依赖:

select distinct  a.Parent,b.Child from Ancestry  a,Ancestry b
where  concat(a.Parent,b.Child not in (
select concat(a.Child,b.Child) from Ancestry a,Ancestry b
where a.Parent = b.Parent and a.Child <> b.Child)
order by a.Parent,b.Child;

我也很欣赏任何替代方法。

2 个答案:

答案 0 :(得分:0)

使用您的示例,您可以解决子项中父项名称的子集,如果父项名称包含在dependents的名称中。如果是这样,请考虑联合查询:

# GREAT-GRANDPARNTS
SELECT DISTINCT Null As Parent, Parent As Dependent
FROM Ancestry
WHERE Len(Parent) = 1

UNION

# GRANDPARNTS
SELECT DISTINCT Left(Parent, 1) As Parent, Parent As Dependent
FROM Ancestry
WHERE Len(Parent) = 3

UNION

# PARENTS
SELECT DISTINCT Left(Child, 1) As Parent, Child As Dependent
FROM Ancestry
WHERE Len(Child) > 3

UNION

# CHILDREN
SELECT DISTINCT Left(Child, 3) As Parent, Child As Dependent
FROM Ancestry
WHERE Len(Child) > 3;

当然,根据实际的祖先名称模式调整Len()Left()Mid()字符串函数并扩展(即孙子)。如果子字符串值中没有父项引用,则此解决方案将无效。

答案 1 :(得分:0)

This may work

select p.parent, c.child
from       Ancestry  p
left join  Ancestry  c   on p.parent = left(c.child, len(p.parent))