PostgreSQL 检查数组是否包含左侧数组中的任何元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21742929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:18:45  来源:igfitidea点击:

PostgreSQL check if array contains any element from left-hand array

arrayspostgresqlset-intersection

提问by Lander

I know that in PostgreSQL you can run a query like:

我知道在 PostgreSQL 中你可以运行如下查询:

SELECT (1 = ANY('{1,3,4,7}'::int[])) AS resultto check if the right-hand array contains the element 1. I was wondering if there is an easy way to check if the right-hand array contains any element from the left-handarray. Something like:

SELECT (1 = ANY('{1,3,4,7}'::int[])) AS result检查右侧数组是否包含元素1。我想知道是否有一种简单的方法可以检查右侧数组是否包含左侧数组中的任何元素。就像是:

SELECT ('{2,3}'::int[] = ANY('{1,3,4,7}'::int[])) AS result

SELECT ('{2,3}'::int[] = ANY('{1,3,4,7}'::int[])) AS result

Is there an easy way to do this without iterating over the left-hand loop myself?

有没有一种简单的方法可以做到这一点而无需自己迭代左侧循环?

回答by Craig Ringer

Sure, use the &&array-overlaps operator:

当然,使用&&数组重叠运算符:

SELECT ARRAY[1,2] && ARRAY[1,3,4,7];

See array functions and operators.

请参阅数组函数和运算符

回答by Daniel Sparing

Assuming that your inputs are arrays but it is okay to unwrap them using unnest(), here is a solution:

假设您的输入是数组,但可以使用 展开它们unnest(),这是一个解决方案:

SELECT count(*)>0
FROM
    (SELECT unnest('{2,3}'::int[]) a1) t1
    join (SELECT unnest('{1,3,4,7}'::int[]) a2) t2
        on t1.a1=t2.a2;