我有一个包含父/子关系结构的表。
有三种类型的实体:
示例结构
id parent name type
28 0 Head Group 100
10 28 --Location 1 1
12 28 --Location 2 1
16 28 --Location 3 1
17 28 --Location 4 1
19 28 --Location 5 1
29 28 --Location 6 1
8 28 -Sub Group 1 10
11 8 --Sub Group 1 Location 1 1
30 28 -Sub Group 2 10
13 30 --Sub Group 2 Location 1 1
14 30 --Sub Group 2 Location 2 1
15 30 --Sub Group 2 Location 3 1
如果传入1d 28(头部组),我希望能够选择所有行。
我试图创建一个声明,但我认为这超出了我的范围。任何帮助将不胜感激......
SELECT CGroup.id,
CGroup.parent,
CGroup.name,
CGroup.type
FROM Customer AS CGroup
INNER JOIN Customer AS CSubGroup
ON CSubGroup.parent_id = CGroup.id
WHERE CGroup.parent_id=28
答案 0 :(得分:1)
你让它太复杂了。把事情简单化。简单查询通常执行得更快,错误更少。
// first get all subgroups under the main group
subGroupIds = fetchField('
select group_concat(id)
from CGroup
where parent = 28
and type = 10
')
// then get everything
results = fetchRows('
select *
from CGroup
where parent = 28
or parent in (subGroupIds)
')
如果你真的想这么做"正确",我建议你实施Nested Set tree。