相关疑难解决方法(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_length 如果数组为空行为

请向我解释这种行为。

此 SQL 查找 ids (type is array::bigint) 为空的元素。

SELECT * FROM rises WHERE ids = '{}'
-- finds, e.g., 9 rows
Run Code Online (Sandbox Code Playgroud)

此 SQL 未找到任何行:

SELECT * FROM rises WHERE array_length(ids, 1) = 0
--finds always 0 rows
Run Code Online (Sandbox Code Playgroud)

但是这个 SQL 可以找到非空数组

SELECT * FROM rises WHERE array_length(ids, 1) > 0
--finds, e.g., 15 rows
Run Code Online (Sandbox Code Playgroud)

初始化:

CREATE TABLE rises(
    id bigserial, 
    d1 bigint DEFAULT 0, 
    ids bigint[] DEFAULT '{}', 
    PRIMARY KEY (id));
Run Code Online (Sandbox Code Playgroud)

为什么array_length可以找到非空数组,但对空数组不起作用?

postgresql array

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

array ×2

postgresql ×2