sql - 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
查询看起来如何?
解决方案
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[];
推荐阅读
- python - 如何将等级添加到 discord.py 机器人的经验升级系统?
- c# - 即使使用有效的连接字符串,也得到“请求的 URI 不代表服务器上的任何资源”
- security - Access-Control-Allow-Origin:当我在 Nginx 和 Tomcat 中设置值时检测到 null
- express - 如何保护我的令牌端点只能从同一域中提供的 SPA 调用?
- javascript - 动态网格上的单元格选择问题(Javascript / HTML)
- pandas - 如何将熊猫数据框转换为箭头数据集?
- android - 无法在 ARM Mac 上 IntelliJ 的 Android 模拟器上运行 Flutter 项目,表示该模拟器不适用于“main.dart”配置
- c# - DbContextOptions 如何被注入?
- javascript - 列中的平均值并通过javascript对所有行求和
- graphql - 在 graphql 的嵌套解析器中处理可为空的关系