检查数组中是否存在一个值非常简单.例如,以下内容将返回true.
SELECT 'hello' = ANY(ARRAY['hello','bees'])
但是,如果我想检查数组中是否存在多个值,该怎么办?例如,如果数组中存在’hello’或’bye’,我想返回true.我想做点什么
SELECT ['hello','bye'] = ANY(ARRAY['hello','bees'])
但这似乎不起作用.
编辑:
我还想弄清楚如何检查多个值是否具有公共前缀的数组中是否存在多个值.
例如,如果我想在数组包含前缀为’hello’的任何元素时返回true.所以我基本上想要类似的东西
SELECT ARRAY['hello%'] && ARRAY['helloOTHERSTUFF']
是真实的.
要检查另一个数组中是否存在任何数组元素,请使用重叠
&&
运算符,如下所示:
SELECT ARRAY[1,4,3] && ARRAY[2,1] -- true
检查每个数组元素是否与您可以使用的特定模式unnest(anyarray)
(提取数组元素)功能结合使用LIKE or POSIX Regular Expressions(应用模式匹配)和聚合bool_and(expression)
– 执行按位AND运算符并返回一行输出.
测试用例:
我已将数组元素放在单独的行中以阐明哪个比较产生真和哪个假.
SELECT bool_and(array_elements) FROM ( SELECT unnest( ARRAY[ 'hello',-- compared with LIKE 'hello%' yields true 'helloSOMething',-- true 'helloXX',-- true 'hell',-- false 'nothing' -- false ]) ~~ 'hello%' ) foo(array_elements);
因此,如果任何比较结果为false,则bool_and(array_elements)将返回false.
注意:如果需要将数组与多个模式进行比较,可以使用POSIX比较并使用|代表另类.举个例子,假设我们想知道数组的每个元素是以hello还是不以单词开头的:
SELECT bool_and(array_elements) FROM ( SELECT unnest( ARRAY[ 'hello',-- true 'helloSOMething',-- false (doesn't start with neither "hello" nor "not") 'nothing' -- true (starts with not) ]) ~ '^hello|not' -- note the use of ~ instead of ~~ as earlier (POSIX vs LIKE) ) foo(array_elements);