相关疑难解决方法(0)

按公共数组元素的计数对结果进行排序

使用 Postgres 9.4,我有兴趣拥有一个整数数组,例如user_ids_who_like并提供一个用户数组(例如user_ids_i_am_following)来对该交集进行排序。

就像是:

select * 
from items 
where [there is an intersection between 
       user_ids_who_like with user_ids_i_am_following] 
order by intersection(user_ids_who_like).count
Run Code Online (Sandbox Code Playgroud)

是否可以通过数组交集进行分组和排序?

示例数据:

items
name          | user_ids_who_like
'birds'       | '{1,3,5,8}'
'planes'      | '{2,3,4,11}'
'spaceships'  | '{3,4,6}'
Run Code Online (Sandbox Code Playgroud)

对于给定的user_ids_who_i_follow = [3,4,11],我可以执行以下操作:

select * from items
where <user_ids_who_like intersects with user_ids_who_i_follow>
order by <count of that intersection>
Run Code Online (Sandbox Code Playgroud)

想要的结果:

name          | user_ids_who_like  | count
'planes'      |  '{2,3,4,11}'      | 3
'spaceships'  |  '{3,4,6}'         | 2
'birds'       |  '{1,3,5,8}'       | 1 …
Run Code Online (Sandbox Code Playgroud)

postgresql array

6
推荐指数
1
解决办法
2405
查看次数

标签 统计

array ×1

postgresql ×1