学习SQL,并有一些问题。我有2个表level
和level_hierarchy
|name | id | |parent_id | child_id|
------------------- ---------------------
| Level1_a | 1 | | NULL | 1 |
| Level2_a | 19 | | 1 | 19 |
| Level2_b | 3 | | 1 | 3 |
| Level3_a | 4 | | 3 | 4 |
| Level3_b | 5 | | 3 | 5 |
| Level4_a | 6 | | 5 | 6 |
| Level4_b | 7 | | 5 | 7 |
现在我需要的是一个查询,该查询将基于参数指示我要从中获取条目的级别层次结构级别的参数,从每个层次结构级别返回表level
中的所有条目。
获取Level1
项非常容易。
SELECT name FROM level INNER JOIN level_hierarchy ON level.id =
level_hierarchy.child_id WHERE level_hierarchy.parent_id=NULL
Level2
项:
Level2_a
Level2_b
只是具有父级的那些,而其父级的父级是NULL
,依此类推。我怀疑这是递归的来源。
有人可以指导吗?
答案 0 :(得分:3)
很好的问题,递归在SQL中是一个困难的话题,其实现因引擎而异。感谢您使用PostgreSQL标记您的帖子。 PostgreSQL有一些出色的documentation on the topic。
WITH RECURSIVE rec_lh(child_id, parent_id) AS (
SELECT child_id, parent_id FROM level_hierarchy
UNION ALL
SELECT lh.child_id, lh.parent_id
FROM rec_lh rlh INNER JOIN level_hierarchy lh
ON lh.parent_id = rlh.child_id
)
SELECT DISTINCT level.name, child_id
FROM rec_lh INNER JOIN level
ON rec_lh.parent_id = level.id
ORDER BY level.name ASC;
另请参见:
答案 1 :(得分:3)
您对第一级的查询(此处为depth
与表的区别)应如下所示:
select l.name, h.child_id, 1 as depth
from level l
join level_hierarchy h on l.id = h.child_id
where h.parent_id is null;
name | child_id | depth
----------+----------+-------
Level1_a | 1 | 1
(1 row)
请注意正确使用is null
(不要使用=
与null
进行比较,因为它总是给出null
)。
您可以将以上内容用作递归cte中的初始查询:
with recursive recursive_query as (
select l.name, h.child_id, 1 as depth
from level l
join level_hierarchy h on l.id = h.child_id
where h.parent_id is null
union all
select l.name, h.child_id, depth + 1
from level l
join level_hierarchy h on l.id = h.child_id
join recursive_query r on h.parent_id = r.child_id
)
select *
from recursive_query
-- where depth = 2
name | child_id | depth
----------+----------+-------
Level1_a | 1 | 1
Level2_b | 3 | 2
Level2_a | 19 | 2
Level3_a | 4 | 3
Level3_b | 5 | 3
Level4_a | 6 | 4
Level4_b | 7 | 4
(7 rows)