查询数组列是否包含一个或多个值

时间:2019-09-19 11:24:39

标签: mysql ruby-on-rails

我有一个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

而且我也不能更改版本,因为它是现有项目。

任何解决方案?

1 个答案:

答案 0 :(得分:0)

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

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

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