我有足够的挑战来解决这个问题,但我没有足够的挑战在 MySQL 中解决它。考虑到这一点,这是您的问题的 Postgresql 版本:
with recursive
skill_list(skill_id) as
(
select distinct skill_id from skill_req
where req is not null
union
select distinct req from skill_req
where req is not null
)
,skill_tree(skill_group, depend_on) as
(
select skill_id, skill_id -- seeds
from skill_list
union
select st.skill_group, sr.req
from skill_req sr
join skill_tree st
on sr.skill_id = st.depend_on
)
,skills_required as
(
select skill_group, depend_on
from skill_tree
where skill_group <> depend_on -- remove seeds
)
select
sl.skill_id,
array_agg(sr.depend_on order by depend_on) as array_version,
array_to_string(array_agg(sr.depend_on order by depend_on), ',')
as group_concat_version
from skill_list sl
left join skills_required sr on sr.skill_group = sl.skill_id
group by sl.skill_id
数据:
CREATE TABLE skill_req
(skill_id int, req int);
INSERT INTO skill_req
(skill_id, req)
VALUES
(2, 1),
(4, 3),
(5, 1),
(6, 4),
(6, 2),
(7, 6),
(7, 9),
(8, 2),
(8, 5),
(9, 3),
(10, 4),
(10, 5),
(10, 9);
输出:
skill_id | array_version | group_concat_version
----------+---------------+----------------------
1 | {NULL} |
2 | {1} | 1
3 | {NULL} |
4 | {3} | 3
5 | {1} | 1
6 | {1,2,3,4} | 1,2,3,4
7 | {1,2,3,4,6,9} | 1,2,3,4,6,9
8 | {1,2,5} | 1,2,5
9 | {3} | 3
10 | {1,3,4,5,9} | 1,3,4,5,9
(10 rows)
现场测试:http ://www.sqlfiddle.com/#!1/77894/1