检查 Postgres 数组中是否存在值 [英] Check if value exists in Postgres array

查看:54
本文介绍了检查 Postgres 数组中是否存在值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Postgres 9.0,我需要一种方法来测试给定数组中是否存在某个值.到目前为止,我想出了这样的事情:

Using Postgres 9.0, I need a way to test if a value exists in a given array. So far I came up with something like this:

select '{1,2,3}'::int[] @> (ARRAY[]::int[] || value_variable::int)

但我一直认为应该有一个更简单的方法,我就是看不到它.这似乎更好:

But I keep thinking there should be a simpler way to this, I just can't see it. This seems better:

select '{1,2,3}'::int[] @> ARRAY[value_variable::int]

我相信它就足够了.但如果您有其他方法可以做到,请分享!

I believe it will suffice. But if you have other ways to do it, please share!

推荐答案

使用 ANY 结构更简单:

Simpler with the ANY construct:

SELECT value_variable = ANY ('{1,2,3}'::int[])

ANY 的右操作数(在括号之间)可以是 set(例如子查询的结果)数组.有几种使用方法:

The right operand of ANY (between parentheses) can either be a set (result of a subquery, for instance) or an array. There are several ways to use it:

重要区别:数组运算符(<@@>&& 等) expect array 类型作为操作数和支持标准中的 GIN 或 GiST 索引PostgreSQL 的分布,而 ANY 构造期望 element 类型作为左操作数,并且不支持这些索引.示例:

Important difference: Array operators (<@, @>, && et al.) expect array types as operands and support GIN or GiST indices in the standard distribution of PostgreSQL, while the ANY construct expects an element type as left operand and does not support these indices. Example:

这些都不适用于 NULL 元素.测试 NULL:

None of this works for NULL elements. To test for NULL:

这篇关于检查 Postgres 数组中是否存在值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆