SQL查询,使用数组列的特定项目搜索所有行

时间:2019-06-17 12:28:02

标签: sql arrays postgresql

我在final class Document: Object { @objc dynamic var createdByUserId: String? @objc dynamic var creationDate: Date? @objc dynamic var userId: String? } 数据库中的SQL情况

postgres:9.6

我需要找到所有带有数字CREATE TABLE my_table ( id serial PRIMARY KEY, numbers INT [] ); INSERT INTO my_table (numbers) VALUES ('{2, 3, 4}'); INSERT INTO my_table (numbers) VALUES ('{2, 1, 4}'); -- which means -- test=# select * from my_table; id | numbers ----+--------- 1 | {2,3,4} 2 | {2,1,4} (2 rows) 和/或1的行。根据{{​​3}},我使用这样的查询:

2

并出现以下错误:

SELECT * FROM my_table WHERE numbers = ANY('{1,2}'::int[]);

正确的LINE 1: SELECT * FROM my_table WHERE numbers = ANY('{1,2}'::int[]); ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. 查询外观如何?

1 个答案:

答案 0 :(得分:2)

使用var = ANY(array)可以很好地发现数组中是否包含单个值(var)。

要检查一个数组是否包含另一个数组的各个部分,可以使用&& operator

  

&&-重叠(具有相同的元素)-ARRAY [1,4,3] && ARRAY [2,1]-> true

SELECT * FROM my_table WHERE numbers && '{1,2}'::int[];

要检查一个数组是否包含另一个数组的所有成员,可以使用@>运算符

  

@>-包含-ARRAY [1,4,3] @> ARRAY [3,1]->是

SELECT * FROM my_table WHERE numbers @> '{1,2}'::int[];