sql - 查询 int 是否在数组列内部,Postgres 和 Rails

标签 sql ruby-on-rails arrays postgresql

我有一个表,其中有一列整数数组类型。 给定一个整数作为输入,我想查询该列名为的行 tipo_propiedad 包含输入整数。 直接在 Postgres 中可以通过使用 && 运算符并将输入 int 转换为数组来工作。 问题是使用这个:

Zone.where("tipo_propiedad && ?", [].push(type)).count

其中 type 是输入整数,给出

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,这就给出了

SELECT COUNT(*) FROM "zonas" WHERE (tipo_propiedad && 5,1) PG::UndefinedFunction: ERROR: operator does not exist: integer[] && integer

我也在使用 squeel 但该 gem 没有任何运算符来执行此操作。

最佳答案

你可以做任何一个

Zone.where("'?' = ANY (tipo_propiedad)", 1)

Zone.where("tipo_propiedad && ARRAY[?]", 1)
                     # or "&& '{?}'"

关于sql - 查询 int 是否在数组列内部,Postgres 和 Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27862674/

相关文章:

ruby-on-rails - Rails 3 迁移更改浮点长度/小数

javascript - 比较包含数组的对象

java - Arraylist addAll() 方法抛出异常

javascript - 我如何创建一个可重用的函数来为变量对象属性设置状态?

php - sql PDO fetchall 重复的对象键?

javascript - 我的 JavaScript 脚本不会在 php 中回显

mysql - 按优先级 NULL 分组?

MySQL - 根据另一个列值搜索列值

ruby-on-rails - 切换到 Redis 缓存后用户注销

ruby-on-rails - 是否可以使用我们尚未安装的 rails 版本创建新的 rails 应用程序?