简体   繁体   English

比较 PostgreSQL 中的 arrays

[英]Compare arrays in PostgreSQL

I have a table in postgres with a value column that contains string arrays.我在 postgres 中有一个表,其value列包含字符串 arrays。 My objective is to find all arrays that contain any of the following strings: {'cat', 'dog'}我的目标是找到所有包含以下任何字符串的 arrays: {'cat', 'dog'}

id  value
 1  {'dog', 'cat', 'fish'}
 2  {'elephant', 'mouse'}
 3  {'lizard', 'dog', 'parrot'}
 4  {'bear', 'bird', 'cat'}

The following query uses ANY() to check if 'dog' is equal to any of the items in each array and will correctly return rows 1 and 3:以下查询使用ANY()检查 'dog' 是否等于每个数组中的任何项,并将正确返回第 1 行和第 3 行:

select * from mytable where 'dog'=ANY(value);

I am trying to find a way to search value for any match in an array of strings.我正在尝试找到一种方法来搜索字符串数组中任何匹配项的value For example:例如:

select * from mytable where ANY({'dog', 'cat'})=ANY(value);

Should return rows 1, 3, and 4. However, the above code throws an error.应该返回第 1、3 和 4 行。但是,上面的代码会引发错误。 Is there a way to use the ANY() clause on the left side of this equation?有没有办法在这个等式的左边使用 ANY() 子句? If not, what would be the workaround to check if any of the strings in an array are in value ?如果没有,检查数组中的任何字符串是否在value中的解决方法是什么?

You can use && operator to find out whether two array has been overlapped or not.您可以使用&&运算符找出两个数组是否重叠。 It will return true only if at least one element from each array match.仅当每个数组中至少有一个元素匹配时,它才会返回 true。

Schema and insert statements:模式和插入语句:

 create table mytable (id int, value text[]);
 insert into mytable values (1,'{"dog", "cat", "fish"}');
 insert into mytable values (2,'{"elephant", "mouse"}');
 insert into mytable values (3,'{"lizard", "dog", "parrot"}');
 insert into mytable values (4,'{"bear", "bird", "cat"}');

Query:询问:

 select * from mytable where array['dog', 'cat'] && (value);

Output: Output:

id ID value价值
1 1 {dog,cat,fish} {狗,猫,鱼}
3 3 {lizard,dog,parrot} {蜥蜴,狗,鹦鹉}
4 4 {bear,bird,cat} {熊,鸟,猫}

db<>fiddle here db<> 在这里摆弄

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM