使用MS SQL SERVER。
表1 core_person
person_id, first_name, last_name
1 Joe Doe
2 Jill Doe
表2 core_profile
profile_id, parent_profile_id, profile_name
1 NULL Main Campus
2 1 Adult
3 2 Usher
4 1 Children
5 4 Teacher
表3 core_profile_member
profile_id, person_id
3 1
5 2
5 1
根据提供的样本数据,所需的输出如下所示
person_id, first_name, last_name, Adults, Childrens
1 Joe Doe T T
2 Jill Doe F T
SQL新手 - 我了解如何构建树结构,但我不知道如何搜索它的特定部分。
我需要能够搜索每个树枝,并为每个“部门”返回一个真/假,以确定该个人是否正在服务。因此,如果person_id出现在Adults分支下的任何标记中,则返回True。到目前为止,我能够调整我在网上找到的树查询,以指定顶级校园标记,但我不知道如何递归检查各个记录。
WITH Serving_Tree AS (
-- Anchor query: Get the root records
SELECT profile_id, parent_profile_id, profile_name
FROM core_profile
-- This parent_profile_id would be the Campus tag
WHERE parent_profile_id = '448'
UNION ALL
-- Recursive query: Get the records of the next level
SELECT child.profile_id, child.parent_profile_id, child.profile_name
FROM core_profile AS child
INNER JOIN Attrs AS parent
ON child.parent_profile_id = parent.profile_id
)
SELECT profile_id, parent_profile_id,profile_name
FROM Serving_Tree