Postgres-如何查找某一列的最大交集的行

时间:2018-07-14 19:56:14

标签: sql arrays postgresql postgresql-10

我有一个名为Protocols的表,其中包含一个名为keyWords的列,该列的类型为TEXT[]。 给定一个字符串数组,如何获得keyWords列与给定数组的最大交集的行?

1 个答案:

答案 0 :(得分:4)

使用该功能(在其他地方也可以使用):

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.