Postgresql - 检查给定的字符串是否以字符串数组的任何元素开头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39019715/
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 02:22:12  来源:igfitidea点击:

Postgresql - Check if a given string starts with any element of the array of strings

arrayspostgresql

提问by postgresql_beginner

Given two strings we can do:

给定两个字符串,我们可以这样做:

select 'aaa123' ilike 'aaa'||'%'

The result will be TRUE. I would like to do the same thing with a string and an array - if the given string starts with any of the elements of the array of strings than the result would show TRUE.

结果将是 TRUE。我想对字符串和数组做同样的事情 - 如果给定的字符串以字符串数组的任何元素开头,那么结果将显示为 TRUE。

For example (array and string):

例如(数组和字符串):

select array['aaa123'::text,'bbb123'::text] as text_array
select 'aaa12345' as string

I would like to do something like this:

我想做这样的事情:

select string ilike ANY(text_array || '%')

And I would expect TRUE since aaa12345 starts with aaa123 (element of the array).

我希望 TRUE ,因为 aaa12345 以 aaa123 (数组的元素)开头。

Thanks a lot for the help!

非常感谢您的帮助!

采纳答案by Kamil Gosciminski

You could unnest()the array of strings and then compare your input string with every element like you wanted.

您可以unnest()将字符串数组与您想要的每个元素进行比较。

You would get as many rows in the output as there are elements in your array. Since you need a clear indicator whether any of the comparison against array element yields true use bool_or()aggregate function:

您将在输出中获得与数组中的元素一样多的行。由于您需要一个明确的指标是否与数组元素的任何比较产生真正的使用bool_or()聚合函数:

select 
  bool_or('string12345' ilike arr_element||'%') 
from 
  unnest(ARRAY['string123','something']::text[]) x(arr_element);

This would give you TRUEsince:

这会给你TRUE因为:

SELECT 'string12345' ilike 'string123%' -- true

Note: bool_or()returns true if at least one input value is true, otherwise false.

注意:bool_or()如果至少有一个输入值为真,则返回真,否则为假。

回答by Clodoaldo Neto

select string ilike ANY(
    select s || '%'
    from unnest(text_array) s(s)
    )

回答by Pawe? Dyl

You can use EXISTSwith unnestas follows:

您可以使用EXISTS具有unnest如下:

SELECT EXISTS (SELECT * FROM unnest(text_array) a WHERE 'aaa1234' ILIKE a||'%')