查询int是否在数组列内,Postgres with Rails [英] Querying if an int is inside of an array column, Postgres with Rails
问题描述
我有一个表格,其中有一列类型为整数数组。
给定整数作为输入,我想查询名为
tipo_propiedad的列包含输入整数的行。
直接在Postgres中可以通过使用&&运算符并将输入int强制转换为数组。
问题是使用此方法:
I have a table with a column of type integer array. Given an integer as input I want to query for the rows where this column named tipo_propiedad contains the input integer. Directly in Postgres that may work by using && operator and casting the input int to an array. The thing is that using this:
Zone.where("tipo_propiedad && ?", [].push(type)).count
其中type是输入整数,给出
Where type is the input integer, gives
在 zonas中选择COUNT(*)(tipo_propiedad& 1)
PG :: UndefinedFunction:错误:运算符不存在:整数[]&&整数
SELECT COUNT(*) FROM "zonas" WHERE (tipo_propiedad && 1) PG::UndefinedFunction: ERROR: operator does not exist: integer[] && integer
我也尝试了
Zone.where("tipo_propiedad && ?", [5].push(type))
因为tipo_propiedad内部只有1个,2个或3个,所以
because tipo_propiedad would only have 1, 2 or 3 inside and that gives
从 zonas中选择COUNT(*)( tipo_propiedad&&&& 5,1)
PG :: UndefinedFunction:错误:运算符不存在:integer []&&整数
SELECT COUNT(*) FROM "zonas" WHERE (tipo_propiedad && 5,1) PG::UndefinedFunction: ERROR: operator does not exist: integer[] && integer
我也在使用squeel,但是gem没有任何运算符。
I'm also using squeel but that gem doesn't have any operator to do this.
推荐答案
您可以选择
Zone.where("'?' = ANY (tipo_propiedad)", 1)
或
Zone.where("tipo_propiedad && ARRAY[?]", 1)
# or "&& '{?}'"
这篇关于查询int是否在数组列内,Postgres with Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!