我有一个这样的查询:
select id, array_length(users_who_like_ids,1) as ct
from queryables
order by 2 desc;
Run Code Online (Sandbox Code Playgroud)
但是空数组(没有元素)排在最前面。array_length()
对于这种情况,我宁愿返回 0,以便将其排序到底部。
我可能不理解array_length()
(好吧,绝对)但是:
embers_dev2=# select array_length(array[1,2], 1), array_length(ARRAY[]::integer[],1);
Run Code Online (Sandbox Code Playgroud)
应该返回 0 而不是没有(NULL),对吗?
我可以在上面做一个像内联这样的 if 语句吗?
根据关于 SO 的这个相关答案,它看起来COALESCE
可能是我想要的 - 但我愿意接受更好的想法:
使用 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) 我正在处理启用了intarray扩展的 Postgres 9.4项目。我们有一个看起来像这样的表:
items
-------------------------------------
id name tag_ids
--------------------------------------
1 a car {1,4}
2 a room to rent {1}
3 a boat {1,2,4,11}
4 a wine {2}
5 emily {3}
Run Code Online (Sandbox Code Playgroud)
如果可能,我想对标签 ID 进行分组。就像获取具有tag_id
“{1,2,4,11}”的所有元素的计数
tag_id count
1 3
2 2
4 2
11 1
Run Code Online (Sandbox Code Playgroud)
这可能吗?我会认为这样的交叉点:
select * from items where tag_ids && '{1,2,4,11}'
Run Code Online (Sandbox Code Playgroud)
但我需要按交集结果内的数组元素进行分组。如果我按 tag_ids 分组,它只是唯一值。
我该怎么做?
使用 Postgres 9.4,我有一个page_views
包含一page
列的表。我想选择所有不同的页面并在它们之前进行计数并按降序对它们进行排序。我还希望在过去 24 小时内最少计数 20。所以它看起来像这样:
120 / home
56 / about
24 / locations
Run Code Online (Sandbox Code Playgroud)
我刚在想:
select count(*),page from page_views group by page where count(*) > 20;
Run Code Online (Sandbox Code Playgroud)
但这不起作用。这该怎么做?
我在 Postgres 9.6 db 中有一个表,其结构如下:
Table "public.pricings"
Column | Type | Modifiers
---------------------------+-----------------------------+-------------------------------------------------------
id | integer | not null default nextval('pricings_id_seq'::regclass)
unconfirmed_matrix_prices | jsonb | not null default '"{}"'::jsonb
Run Code Online (Sandbox Code Playgroud)
我是使用 jsonb 的新手。
我想搜索任何空的 unconfirmed_matrix_prices(即默认值)。我看到我可以做这样的事情:
solar_dev=# select count(*) from json_object_keys('{"f1":1,"f2":2}');
count
-------
2
(1 row)
Run Code Online (Sandbox Code Playgroud)
有没有办法可以做一个 where 短语,其中 json_object_keys 等于 0?我知道一些变通的方法 - 有更好的方法吗?