递归查找每行的父级和子级

问题描述 投票:0回答:1

我有一个包含 client_id 和parent_clientid 的表。每个客户端都可以是父级,并且可以包含多个子级。我想知道,对于每一行,如何在连接字符串中获取关联的父级和子级(如示例中所示)。我不想根据客户端 ID 或主客户端 ID 运行查询。预期的结果字符串应该列出该 clientid 的存在(无论它出现在何处)。可以吗?

client_id primary_client_id 预期结果
1 1,10,11,57,65
2 2,3,4,6,56
3 2 2,4,6,56
4 2 2,3,6,56
6 2 2,3,4,56
7 7,8,9,58,59
8 7 7,9,58,59
9 7 7,8,58,59
10 1 1,11,57,65
11 1 1,10,57,65
48 48,49,50,52
49 48 48,50,52
50 48 48,49,52
51 51
52 48 48,49,50
53 53
54 54
55 55
56 2 2,3,4,6
57 1 1,10,11,65
58 7 7,8,9,59
59 7 7,8,9,58
60 60
61 61
62 62
63 63
64 64
65 1 1,10,11,57,65

enter image description here

with recursive myCTE (root_id, client_id, firstname, lastname, primary_client_id) as (
    # the most basic level, we need to remember the root id and name
    select client_id as root_id,
           client_id,
           firstname,
           lastname,
           primary_client_id
    from clients
    union all
    select mC.root_id,
           cl.client_id,
           mC.firstname,
           mC.lastname,
           cl.primary_client_id
    from clients cl
    inner join myCTE mC on cl.primary_client_id = mC.client_id
    
)
select * from (
select root_id, group_concat(client_id order by client_id ASC) as simple_skus
from myCTE
group by root_id
) t1 
mysql parent-child common-table-expression recursive-cte
1个回答
0
投票

事情是这样的,如果没有像 client_id 这样的起点,编写一个查询来获取表中每条记录的链可能会是一个性能噩梦。我能想到的最接近的方法是获取所有可能的“家谱”并将它们连接在一起。这里的问题是你会让每个客户多次列出(在他们所属的任何/每个组中)。不幸的是,数据库并不是为了以超高效的方式处理这种递归关系跟踪而构建的。

© www.soinside.com 2019 - 2024. All rights reserved.