gpt4 book ai didi

ruby-on-rails - Hstore 查询以使用 ruby​​ on rails 查找与任何数组元素匹配的记录

转载 作者:行者123 更新时间:2023-11-29 13:09:39 24 4
gpt4 key购买 nike

我在数据库表中有一个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

最佳答案

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

hstore ? key # does hstore contain key?

查询可能如下所示:

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

根据 postgresql docs

Check for a specific key in hstore column You can check for a specific key in an hstore column using the ? operator in the WHERE clause. For example, the following statement returns all rows with attr contains key publisher.

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

关于ruby-on-rails - Hstore 查询以使用 ruby​​ on rails 查找与任何数组元素匹配的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56650373/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com