首页 > 解决方案 > 查询数组列是否包含一个或多个值

问题描述

我有一个 PropertyPromotion 模型,它有一个称为平台的属性,其值为数组数据类型。我需要查询其平台属性具有某些特定数组中存在的值的所有 PropertyPromotion。

例如:我有一个数组

platform = ["android"]

PropertyPromotion.platform值可能为 ["android", "iphone"]

我需要返回所有可能将“android”或“iphone”作为其平台数组值之一的 PropertyPromotion

我尝试了以下方法:

PropertyPromotion.where("platform @> ARRAY[?]::varchar[]", platform)
PropertyPromotion.where("platform && ARRAY[?]::varchar[]", platform)
PropertyPromotion.where('platform @> ARRAY[?]::integer[]', platform)

但我得到以下语法错误:-

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@> ARRAY['android']::integer[])' at line 1: SELECT `property_promotions`.* FROM `property_promotions` WHERE (platform @> ARRAY['android']::integer[])

我的mysql版本是mysql Ver 14.14 Distrib 5.7.25, for osx10.14 (x86_64) using EditLine wrapper

而且我也无法更改版本,因为它是一个现有项目。

任何解决方案??

标签: mysqlruby-on-rails

解决方案


ifplatform = ["android"] 是可以使用的字符串数组

PropertyPromotion.where('platform in (#{platform_arr})')

其中 platform_arr 是一个数组,其中包含您想要获取的值
platform_arr = ['android','ios']


推荐阅读