如何在Postgresql中检查数组的子集中是否存在值?

huangapple go评论50阅读模式
英文:

How to check if value in subset of array in Postgresql?

问题

我想在我的WHERE子句中设置一个条件,如果一个文本字段包含在语句中声明的数组的子集中,则返回true。这是使用PostgreSQL v15.1的示例语句:

SELECT 'case_1'::TEXT IN ((ARRAY['case_1', 'case_2', 'case_3'])[1:2]);

这应该声明一个包含case_1、2、3的数组,取数组的子集包含case_1、2,然后测试case_1是否在数组中。期望的结果是true。

实际行为是一个错误:"运算符 text=text[]"。

我理解IN()运算符是测试左操作数是否在右操作数中,右操作数具有一个维度。

如何更正语法以返回true或false,以确定case_1是否在数组的子集中?

英文:

I want put a condition in my WHERE clause that returns true if a text field is contained in a subset of an array declared in the statement. This is using postgres v15.1. I have simplified the statement to the following example:

SELECT 'case_1'::TEXT IN((ARRAY['case_1','case_2','case_3']) [1:2]);

This should declare an array containing the case_1,2,3, take a subset of the array containing case_1,2 and then test if case_1 is in the array. Expected result is true.

Actual behaviour is an error: "Operator does not exist text=text[]".

I understood the IN() operator is a test if the left hand argument is in the right hand argument which has a dimension.

How can I correct the syntax to return true or false if case_1 is in the subset of the array?

答案1

得分: 2

像错误消息所说,你的类型弄混了。

IN 关键字期望在括号中提供一个明确的项目列表。你提供了一个项目 - 一个数组。

你想要使用 ANY(...)

SELECT 'case_1' = ANY((ARRAY['case_1', 'case_2', 'case_3'])[1:2]);
英文:

Like the error says, you've got your types messed up.

The IN keyword expects an explicit list of items in brackets. You have provided it with one item - an array.

You want ANY(...)

SELECT 'case_1' = ANY((ARRAY['case_1', 'case_2', 'case_3'])[1:2]);

huangapple
  • 本文由 发表于 2023年6月13日 17:55:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76463713.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定