mysql – 如何使用表父子关系与SQL仅选择一代分层树?

假设有一个名为people的表,其中包含以下列:

> person_id(整数)
> parent_person_id(整数)
> name(varchar)

现在,假设表格已经填充,名称值只是字母(A,B,C,D ……).考虑到每个人的父母,我们最终得到了一个像下面那样的分层树.值的格式如下:

person_id,parent_person_id,name

> 1,1,A
> 2,2,B

> 3,2,C

> 4,3,D

> 5,2,E

> 6,5,F

> 7,6,G
> 8,6,H

考虑上面的结构,A& B作为第一代,C& E作为第二代,D& F作为第三代和G& H作为第四代.对于第一代元素,parent_person_id等于元素的person_id.

我需要编写一个查询,允许我从树的某一代(第一,第二,第三,第四等)中选择名称.结果,我可以得到一个表格,其中包含来自某一代人的用户名.例如:

第一代

person name  |  parent name
A            |  A
B            |  B

第二代

person name  |  parent name
C            |  B
E            |  B

第三代

person name  |  parent name
D            |  C
F            |  E

第四代

person name  |  parent name
G            |  F
H            |  F

我想传递一个参数来定义每一代应该在下面的查询中列为子代.

SELECT
    child.name as 'person name',
    parent.name as 'parent name'
FROM
    people as child
JOIN 
    people as parent
ON 
    child.parent_person_id = parent.person_id
WHERE
    -- I NEED HELP HERE :)
;

有没有人对如何实现这一点有任何想法?欢迎任何帮助.

最佳答案 这是冗长而丑陋的,而且速度很慢,而且只限于4代,但我不知道如何做到这一点.

SELECT person_name, parent_name FROM

    (SELECT child1.name AS person_name, parent1.name AS parent_name, '1' AS generation
    FROM people as child1
    JOIN people as parent1
    ON child1.parent_person_id = parent1.person_id AND child1.parent_person_id = child1.person_id

    UNION

    SELECT child2.name AS person_name, parent2.name AS parent_name, '2' AS generation
    FROM people as child2
    JOIN people as parent2
    ON child2.parent_person_id = parent2.person_id AND child2.parent_person_id <> child2.person_id AND parent2.parent_person_id = parent2.person_id

    UNION

    SELECT child3.name AS person_name, parent3.name AS parent_name, '3' AS generation
    FROM people as child3
    JOIN people as parent3
    ON child3.parent_person_id = parent3.person_id AND parent3.parent_person_id <> parent3.person_id
    JOIN people as grandparent1
    ON parent3.parent_person_id = grandparent1.person_id AND grandparent1.parent_person_id = grandparent1.person_id

    UNION

    SELECT child4.name AS person_name, parent4.name AS parent_name, '4' AS generation
    FROM people as child4
    JOIN people as parent4
    ON child4.parent_person_id = parent4.person_id AND parent4.parent_person_id <> parent4.person_id
    JOIN people as grandparent2
    ON parent4.parent_person_id = grandparent2.person_id AND grandparent2.parent_person_id <> grandparent2.person_id
    JOIN people as greatgrandparent
    ON grandparent2.parent_person_id = greatgrandparent.person_id AND greatgrandparent.parent_person_id = greatgrandparent.person_id
    ) AS tree

WHERE generation = ?
点赞