MYSQL根据root父选择所有子项(及其子项)

时间:2014-11-04 12:40:08

标签: mysql sql hierarchical-data

我有一个表格设置如下(当然简化)

code |  descx           | parentcode    | levelx
-----+------------------+---------------+--------
FF00 |  Fruit           | ROOT          | 0
VV00 |  Veggies         | ROOT          | 0
F001 |  Citrus Fruits   | FF00          | 1
V001 |  Roots           | VV00          | 1
F002 |  Oranges         | F001          | 2
F003 |  Tangerine       | F001          | 2
F004 |  Grapefruit      | F001          | 2
F005 |  Lemon           | F001          | 2
V002 |  Carrot          | V001          | 2
V003 |  Beetroot        | V001          | 2
V004 |  Radish          | V001          | 2
F101 |  Big Orange      | F002          | 3
F103 |  Small Orange    | F003          | 3

我想要实现的是选择与Fruit相关的所有节点,所以我最终得到的数据集看起来像

code |  descx           | parentcode    | levelx
-----+------------------+---------------+--------
FF00 |  Fruit           | ROOT          | 0
F001 |  Citrus Fruits   | FF00          | 1
F002 |  Oranges         | F001          | 2
F003 |  Tangerine       | F001          | 2
F004 |  Grapefruit      | F001          | 2
F005 |  Lemon           | F001          | 2
F101 |  Big Orange      | F002          | 3
F103 |  Small Orange    | F003          | 3

我尝试了以下MYSQL,但这只是拉出了整个表格

select t.* from 
(
    SELECT 
        c.code, 
        c.descx, 
        c.parentcode,
        c.levelx,
    FROM 
        food c
   left join
     food p
   on
    c.parentcode = p.code
    WHERE 
        c.code = 'FF00'

    UNION ALL

    SELECT 
        child.code, 
        child.descx, 
        child.parentcode,
        child.levelx,
        child.flags
    FROM 
        food child
    INNER JOIN 
        food parent
    ON 
        child.parentcode = parent.code
) as t 

任何建议?

0 个答案:

没有答案