我的用户结构如下:
id name parent_id
1 Mike
2 Jack 1
3 Sam 1
4 Kurt 1
5 Somebody 3
6 Tommy 4
6 etc.. 2
如何在每个用户的第一级嵌套中获得最大引用次数,通过此示例我期望结果:
3 because Jack, Sam, Kurt is a referral of Mike on first level
答案 0 :(得分:1)
假设“第一级”由parent_id IS NULL
和当前版本Postgres 9.4定义:
SELECT parent_id, count(*) AS referral_ct
FROM (
SELECT id AS parent_id
FROM tbl
WHERE t1.parent_id IS NULL
) t1
JOIN tbl t2 USING (parent_id)
GROUP BY 1
ORDER BY 2 DESC
LIMIT 1; -- to only get 1 row with max. referral_ct
只有少数根节点,JOIN LATERAL
可能更快:
SELECT t1.id, t2.referral_ct
FROM (
SELECT id
FROM tbl
WHERE parent_id IS NULL
) t1
LEFT JOIN LATERAL (
SELECT parent_id, count(*) AS referral_ct
FROM tbl
WHERE parent_id = t1.id
GROUP BY 1
) t2 ON true
ORDER BY 2 DESC
LIMIT 1; -- to only get 1 row with max. referral_ct
相关,有更多解释: