【发布时间】:2015-05-04 09:34:16
【问题描述】:
我有一个存储树结构的表。基本上家庭结构是
Category > Sub category > sub sub category
这里的父级是parent_id为0的那个。 我需要通过sql获取任意类别的家族结构。桌子看起来像
cat_id | parent_id | name
-------------------------
1 | 0 | a
2 | 0 | b
3 | 1 | c
4 | 2 | d
5 | 3 | e
6 | 4 | f
所以对于4的cat_id,我需要的结果是
c1.cat_id | c.name | c2.cat_id | c2.name | c3.cat_id | c3.name
2 b 4 d null null
所以对于6的cat_id,我需要的结果是
c1.cat_id | c.name | c2.cat_id | c2.name | c3.cat_id | c3.name
2 b 4 d 6 f
这是我当前使用的代码,它为每个结果提供多行
SELECT c1.name cat1, c1.cat_id cat1_id,c2.name cat2, c2.cat_id cat2_id ,c3.name cat3, c3.cat_id cat3_id
FROM ea_category AS c1
JOIN ea_category AS c2 ON (c2.parent_id = c1.cat_id)
JOIN ea_category AS c3 ON (c3.parent_id = 0)
where c1.cat_id = 4
我做错了什么
【问题讨论】:
-
它为每个结果提供多于两行,因为有两只猫的
parent_id = 0,所以你的最后一个join加入了他们两个 -
是的,我知道,但我只想要孙子的父母