我有一个包含以下列的表格:
child_count | path
------------+-----
| /
| /a
| /a/a
| /a/b
| /a/b/c
| /b
目前只有路径栏有数据。我想知道一个 SQL(最好是 PostgreSQL)查询能够确定每个路径的子计数,如下所示:
child_count | path
------------+-----
2 | /
2 | /a
0 | /a/a
1 | /a/b
0 | /a/b/c
0 | /b
最佳答案
Andomar 在我编辑时打败了我,但我还是会发布我的解决方案,因为它使用了一些 PostgreSQL 特定的东西。
with path_elements as ( select path, array_length(string_to_array(path, '/'),1) as element_count from path_table ) select parent_path, count(child_path) from ( select p.path as parent_path, c.path as child_path from path_elements p left join path_elements c on p.element_count + 1 = c.element_count and substring(c.path, 1, length(p.path)) = p.path ) t group by parent_path order by parent_path;
关于sql - 确定分层路径的子计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4836426/