Mysql - 如何选择子列表中的所有父项?

时间:2016-06-07 16:06:01

标签: mysql sql

我有一个表,其中每个记录包含他的父亲,这个层次结构最多可以有6个级别。下面的查询搜索名为" DEPARTMENT ABCD"的部门的所有父母。此查询完美无缺。

SELECT D2.id, D2.name, D2.id_parent
FROM (
    SELECT
        @d AS _id,
        (SELECT @d := id_parent FROM department WHERE id = _id) AS id_parent,
        @l := @l + 1 AS level
    FROM
        (SELECT 
            @d := (select id from department where name = 'DEPARTMENT ABCD'), 
            @l := 0
        ) initial_level,
        department D
    WHERE @d <> 0
) D1
JOIN department D2 ON D1._id = D2.id
ORDER BY D1.level DESC;

但是,如果我想同时获取多个孩子的父母(使用类似下面的查询),我会收到错误:&#34;错误代码:1242。子查询返回超过1行& #34;

查询错误&#34;子查询返回多行&#34;:

SELECT D2.id, D2.name, D2.id_parent
FROM (
    SELECT
        @d AS _id,
        (SELECT @d := id_parent FROM department WHERE id = _id) AS id_parent,
        @l := @l + 1 AS level
    FROM
        (SELECT 
            @d := (select id from department where name like 'DEPARTMENT %A%'), 
            @l := 0
        ) initial_level,
        department D
    WHERE @d <> 0
) D1
JOIN department D2 ON D1._id = D2.id
ORDER BY D1.level DESC;

我怎样才能同时接收一个以上孩子的父母?

我在SQL小提琴中添加了一个示例:http://sqlfiddle.com/#!9/f182fb/3

1 个答案:

答案 0 :(得分:1)

鉴于层次结构最多可能有6个级别,我建议加入该表6次,以获得所选部门的所有祖先:

select     distinct id, name, id_parent
from       (
            select      d6.id_parent as id6,
                        d5.id_parent as id5,
                        d4.id_parent as id4,
                        d3.id_parent as id3,
                        d2.id_parent as id2,
                        d1.id_parent as id1,
                        d1.id        as id0
            from        department d1
            left join   department d2 on d2.id = d1.id_parent 
            left join   department d3 on d3.id = d2.id_parent 
            left join   department d4 on d4.id = d3.id_parent  
            left join   department d5 on d5.id = d4.id_parent  
            left join   department d6 on d6.id = d5.id_parent
            where       d1.name like 'DEPARTMENT A%'
           ) as h
inner join department d on d.id in (id0, id1, id2, id3, id4, id5, id6)
order by   1;

SQL fiddle