如何计算邻接列表中每个节点的直接子节点数

发布于 2024-09-05 06:55:44 字数 304 浏览 4 评论 0原文

我有使用邻接列表模型表示的分层数据。

TABLE
    ID
    parentID
    title

我想知道,选择每个节点的直接子节点数量的最简单方法是什么?如果可能的话,我想在一次选择中执行此操作,产生像这样的结果集...

RESULTS...
ID     title     childCount
1      test1     10
2      test2     2
3      test3     0
etc...

感谢您的建议!

I have hierarchical data that I represent using the adjacency list model.

TABLE
    ID
    parentID
    title

I am wondering, what is the simplest way to SELECT the number of immediate children for each node? If possible, I'd like to do this in a single select, yielding a resultset like so...

RESULTS...
ID     title     childCount
1      test1     10
2      test2     2
3      test3     0
etc...

Thanks for your advice!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

辞别 2024-09-12 06:55:44

没有标题,

SELECT parentID as ID, COUNT(ID) AS childCount
  FROM Table
  GROUP BY parentID

如果您确实想要标题,我认为您需要自加入(可能慢得多):

SELECT t1.ID as ID, t1.Title as Title, COUNT(t2.ID) as childCount
  FROM Table t1
  LEFT OUTER JOIN Table t2
  ON t1.ID = t2.parentID

Without the title,

SELECT parentID as ID, COUNT(ID) AS childCount
  FROM Table
  GROUP BY parentID

If you do want the title I think you need a self-join (probably way slower):

SELECT t1.ID as ID, t1.Title as Title, COUNT(t2.ID) as childCount
  FROM Table t1
  LEFT OUTER JOIN Table t2
  ON t1.ID = t2.parentID
她比我温柔 2024-09-12 06:55:44

我认为 Alex 忘记了“Group By t2.parentID”,

您也可以尝试:

SELECT t1.ID as ID, t1.Title as Title, COUNT(t2.ID) as childCount 

FROM Table t1
INNER JOIN 表 t2 ON t1.ID = t2.parenID
按 t2.parentID 分组

I think Alex forgot 'Group By t2.parentID'

also you can try:

SELECT t1.ID as ID, t1.Title as Title, COUNT(t2.ID) as childCount 

FROM Table t1
INNER JOIN Table t2 ON t1.ID = t2.parenID
GROUP BY t2.parentID

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文