【问题标题】:How to return a specific key value from an hstore?如何从 hstore 返回特定的键值?
【发布时间】:2014-04-14 00:37:20
【问题描述】:

我有一个 psql 数据库,其中包含一个 hstore 作为列,如下所示: 柱子: "a" => "1", "b" => "2", "c" => "3"

在一个独立的 ruby​​ 脚本中,我正确地访问了我的数据库,但我想为“a”输出一个特定的值,以便它只返回“1”。 当我尝试从循环中执行此操作时,它会输出 "a" => "1"。

require 'rubygems'
require 'pg'
require 'open-uri'
require'activerecord-postgres-hstore'

conn = PGconn.connect("hostname", 1234, '', '', "x", "y", "z")

array = conn.exec('SELECT * FROM database')

  array.each do |uri|
    puts uri['column']
  end

此页面上的文档http://www.postgresql.org/docs/9.1/static/hstore.html 表明您可以使用 hstore -> text 来获取值,但我不确定如何在 ruby​​ 中执行此操作。

我也看到了这个问题how to parse and display hstore key/value in rails,但正如我所说,当我只想要值时,输出给了我键和值。

我还应该说,虽然数据库是使用 rails 创建的,但我不想将它用于此脚本。 任何帮助将不胜感激。

【问题讨论】:

  • 请添加用于检索array 变量(conn.exec() 及相关)的代码。

标签: ruby postgresql hstore


【解决方案1】:

如果您只想提取 column 中的 'a' 键的值,请准确地说出来并让数据库完成工作:

conn.exec(%q{SELECT column -> 'a' FROM database}).each do |_, a|
  # The value will be in `a`, `_` will be the made up column name.
end

或者,如果您想处理其他事情:

conn.exec(%q{SELECT other_column, column -> 'a' as col_at_a FROM database}).each do |row|
  # Look at `row['other_column']` and `row['col_at_a']` ...
end

【讨论】:

  • 这工作得很好,但输出或多或少相同。我还必须在循环中添加 _.values[0] 以获得正确的值。谢谢!
  • 那么您可能想要更像第二种情况,在 SQL 中使用 AS 为其命名,以便您可以按名称将其从哈希中提取出来。
猜你喜欢
  • 2015-01-11
  • 1970-01-01
  • 2011-02-28
  • 2016-10-23
  • 2018-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-25
相关资源
最近更新 更多