postgresql 数组列内的基本计数

fykwrbwg  于 2023-01-30  发布在  PostgreSQL
关注(0)|答案(1)|浏览(146)

我有一个users表,看起来像这样,其中有一个数组列,包含用户正在跟踪的其他用户的ID。

----------------------------------------
| Field                     | Type     |
----------------------------------------
|  id                       | id       |
|  email                    | varchar  |
|  following_users_ids      | array[]  |
----------------------------------------

要为表中的每个用户获取followers的数量(followers_count),SQL查询应该是什么?following_users_ids数组中的following_users_ids的数量基本上是至少有一个用户的数量。
表格内容示例:

--------------------------------------------------
| id       | email        | following_users_ids   |
---------------------------------------------------
| 1        | foo@bar.com  | {2,3}                 |
---------------------------------------------------
| 2        | ffooo@bb.com | {1}                   |
---------------------------------------------------
| 3        | bbb@bbb.com  | {}                    |
---------------------------------------------------

结果:

------------------------------------------------------------------------
| id       | email        | following_users_ids   | followers_count    |
------------------------------------------------------------------------
| 1        | foo@bar.com  | {2,3}                 | 1                  |
------------------------------------------------------------------------
| 2        | ffooo@bb.com | {1,3}                 | 1                  |
------------------------------------------------------------------------
| 3        | bbb@bbb.com  | {}                    | 2                  |
------------------------------------------------------------------------
4jb9z9bj

4jb9z9bj1#

使用自联接:

select c1.*, count(c2) as followers_count
from content c1
left join content c2 on c1.id = any(c2.following_users_ids)
group by c1.id
order by c1.id

db<>fiddle.中测试

相关问题