【问题标题】:how to get the all sub teams from a table table which also includes sub team of team?如何从包含团队子团队的表格中获取所有子团队?
【发布时间】:2020-05-05 21:25:23
【问题描述】:

所以我有一个餐桌团队

团队(id,名称,parentId)。

我的桌队如下:

id      name               parentId
 1      root                null
 2      child1              1
 3      child2              2

所以,我有 teamId= 1 我可以在 parentId 的帮助下获得 teamId 1 的团队以及 teamId 1 的子团队。但是是否有可能获得 child2 因为它是 child1 的子孩子,它是 root 的孩子,即 teamId 1,只有 teamId 信息? 或者为了更容易,是否需要以不同的方式创建表,例如具有多对多关系的 Teams、Subteams 和 TeamSubteam?

Team.find({
            where: {
                or: [{
                    id: teamId
                }, {
                    parentId: teamId
                }]
            },
            fields: ['id']
        }, function (err, teams) { });

【问题讨论】:

标签: sql postgresql hierarchical-data


【解决方案1】:

这是一个简单的递归查询:

with recursive all_teams as ( 
  select *
  from team 
  where teamid = 1 -- or wherever you want to start
  union all
  select sub.*
  from team sub
   join all_teams p on p.id = sub.parentid
)
select *
from all_teams;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 2019-07-13
    相关资源
    最近更新 更多