Sql Postgres-如何找到与某列具有最大交点的行
我有一个名为Sql Postgres-如何找到与某列具有最大交点的行,sql,arrays,postgresql,postgresql-10,Sql,Arrays,Postgresql,Postgresql 10,我有一个名为Protocols的表,其中包含一个名为keyWords的列,类型为TEXT[]。 给定一个字符串数组,如何获得关键字列与给定数组最大交集的行?使用该函数(在其他地方也可能有用): 查询: with cte as ( select id, keywords, cardinality(array_intersect(keywords, '{a,b,d}')) as common_elements from protocols )
Protocols
的表,其中包含一个名为keyWords
的列,类型为TEXT[]
。
给定一个字符串数组,如何获得关键字
列与给定数组最大交集的行?使用该函数(在其他地方也可能有用):
查询:
with cte as (
select
id, keywords,
cardinality(array_intersect(keywords, '{a,b,d}')) as common_elements
from protocols
)
select *
from cte
where common_elements = (select max(common_elements) from cte)
如果您不喜欢该功能:
with cte as (
select id, count(keyword) as common_elements
from protocols
cross join unnest(keywords) as keyword
where keyword = any('{a,b,d}')
group by 1
)
select id, keywords, common_elements
from cte
join protocols using(id)
where common_elements = (select max(common_elements) from cte);
使用该功能(在其他地方也可能有用):
查询:
with cte as (
select
id, keywords,
cardinality(array_intersect(keywords, '{a,b,d}')) as common_elements
from protocols
)
select *
from cte
where common_elements = (select max(common_elements) from cte)
如果您不喜欢该功能:
with cte as (
select id, count(keyword) as common_elements
from protocols
cross join unnest(keywords) as keyword
where keyword = any('{a,b,d}')
group by 1
)
select id, keywords, common_elements
from cte
join protocols using(id)
where common_elements = (select max(common_elements) from cte);