Search code examples
c#sqlpostgresqldapper

How to do hierarchical child count for a set of IDs in PostgreSQL (not a single ID)


I am using this SQL to retrieve hierarchical children count for a comment:

WITH RECURSIVE c AS (
    SELECT "Id", "ParentId"
    FROM public."Comments"
    WHERE "ParentId" = @CommentId
    UNION
    SELECT s."Id", e."ParentId"
    FROM public."Comments" e
    INNER JOIN c s ON s."Id" = e."ParentId"
) SELECT COUNT(*)
  FROM c;

It works as expected.

But how can I transform this SQL to work with a list of IDs, so it returns a dictionary where KEY is an ID from list in parameters and VALUE is a hierarchical count of children?

I am using this SQL with Dapper in C#

Sample "comments" table:

id  | parentId 
---------------
1   | null
2   | 1
3   | 2
4   | null
5   | 4
6   | 5
7   | 5

Input: Array of IDs given to DB

[1, 4]

Output: Dictionary which has ID from input as key and hierarchical children count as value

{1: 2, 4: 3}

P.S.: the code in input and output is just pseudocode


Solution

  • You can use this query to get the result set

    WITH RECURSIVE c AS (
        SELECT id, parentId, parentid as sid
        FROM Comments
        WHERE parentId = ANY(Array [1, 4])
        
        UNION ALL
        
        SELECT e.id, e.parentId, s.sid
        FROM Comments e
        INNER JOIN c s ON s.id = e.parentId
    ) 
    SELECT sid, COUNT(*)
    FROM c
    group by sid;
    

    returns

    sid count
    4   3
    1   2