我有一个名为Protocols
的表,其中包含一个名为keyWords
的列,该列的类型为TEXT[]
。
给定一个字符串数组,如何获得keyWords
列与给定数组最大交集的行?
最佳答案
使用函数(在其他地方也可能有用):
create or replace function array_intersect(anyarray, anyarray)
returns anyarray language sql as $function$
select case
when $1 is null then $2
else
array(
select unnest($1)
intersect
select unnest($2)
)
end;
$function$;
查询:
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)
DbFiddle.
如果您不喜欢该功能:
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);
DbFiddle.
关于sql - Postgres-如何查找某一列的最大交集的行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51342903/