![](/img/trans.png)
[英]How to make a SQL to create a tag hierarchy based on items with the same tags?
[英]SQL - How to check if users are in the same hierarchy?
我想知道用戶是否直接處於父子關系中。
給定我的用戶表架構
User_id | Parent_ID | Name
例如,我有一個 user_id 列表,我想知道它們是否都在同一個層次樹中。
我嘗試過使用 CTE 遞歸。
樣本數據
User_id | Parent_ID | Name
1 | | A
2 | 1 | B
3 | 2 | C
4 | 3 | D
5 | 2 | E
6 | 1 | F
期望的結果:輸入 [2,3,4] => 相同的團隊
輸入 [2,3,6] => 不是同一個團隊
使用頂級父母的parent_id
作為層次標識符:
with recursive hierarchies as (
select user_id, user_id as hierarchy_id
from ttable
where parent_id is null
union all
select c.user_id, p.hierarchy_id
from hierarchies p
join ttable c on c.parent_id = p.user_id
)
select * from hierarchies;
通過將每個user_id
映射到單個hierarchy_id
,您可以加入您的用戶列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.