【问题标题】:Hstore Query to find records matching with any array element using ruby on railsHstore Query 使用 ruby​​ on rails 查找与任何数组元素匹配的记录
【发布时间】:2019-11-01 04:08:30
【问题描述】:

我在数据库表中有一个 hstore 字段。我想使用 ruby​​ on rails 编写一个查询来查找与 hstore 字段的任何散列中的任何数组元素匹配的记录。

 Users Table
 --------------------------------------------------------------------------------
        ID    Name    sectors(hstore) 

        1     Piotr   {"aviation"=>"0", "oil_and_gas" => "50", "transport" => "50"}
        2     reza    {"oil_and_gas" => "70", "energy" => "30"}
        3     pat     {"transport" => "40", "energy" => "60"}
        4     Kim     {"infrastructure" => "20", "healthcare" => "20", "industrial" => "60"}

考虑到上面的测试数据,我想在 hstore 字段上编写一个查询,以获取所有具有任何键的记录,例如 ['oil_and_gas', 'energy', 'transport']

我可以匹配并找到https://nandovieira.com/using-postgresql-and-hstore-with-rails 中提到的单个扇区记录,但我的要求是找到 hstore 哈希具有与数组的任何一个元素匹配的任何一个键的任何记录。

我正在使用 Rails 5.1.6.2,ruby 2.5.3

【问题讨论】:

    标签: ruby-on-rails ruby postgresql rubygems hstore


    【解决方案1】:

    可能您正在寻找以下运算符:

    hstore ? key # does hstore contain key?
    

    查询可能如下所示:

    User.where("sectors ? 'oil_and_gas'")
        .or("sectors ? 'energy'")
        .or("sectors ? 'transport'")
    

    根据postgresql docs

    检查 hstore 列中的特定键您可以检查特定的 使用 ? 键入 hstore 列WHERE 子句中的运算符。为了 例如,以下语句返回 attr 包含的所有行 密钥发布者。

    SELECT
      title,
      attr->'publisher' as publisher,
      attr
    FROM
      books
    WHERE
      attr ? 'publisher';
    

    【讨论】:

    • 谢谢,不错的方法,但我只能找到一种简短的方法来执行此查询:User.where("sectors ?| Array['oil_and_gas', 'energy', '运输']")
    • @kashif 很高兴为您提供帮助。我同意,你的版本更短。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    相关资源
    最近更新 更多