我的表跟随包含int数组中的user_id和follower_ids:
id | user_id | follower_ids
---|---------|-------------
1 | 1 | {2,3,4}
2 | 2 | {1}
3 | 3 | {1,2}
4 | 4 | {1}
我想得到像这样的结果
user_id | count
--------| -----
1 | 3
2 | 2
3 | 1
4 | 1
如何运行查询?
谢谢。
答案 0 :(得分:2)
您可以使用array_length()功能
select user_id
,array_length(follower_ids,1) count
from bar
答案 1 :(得分:0)
WITH t(id,user_id,follower_ids) AS ( VALUES
(1,1,ARRAY[2,3,4]),
(2,2,ARRAY[1]),
(3,3,ARRAY[1,2]),
(3,4,ARRAY[1])
)
SELECT
follower AS user_id,
count(follower) AS follower_count
FROM t,unnest(t.follower_ids) AS follower
GROUP BY 1
ORDER BY 1;
输出:
user_id | follower_count
---------+----------------
1 | 3
2 | 2
3 | 1
4 | 1
(4 rows)