首页 > 解决方案 > SQL 查询,它搜索具有特定数组列项的所有行

问题描述

postgres:9.6我在数据库中的 sql 案例

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和/或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.

正确的sql查询看起来如何?

标签: sqlarrayspostgresql

解决方案


Usingvar = ANY(array)非常适用于查找单个值 ( var) 是否包含在数组中。

要检查一个数组是否包含另一个数组的一部分,您可以使用&& 运算符

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

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

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

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

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

推荐阅读