【问题标题】:Rails3: Postgres Hstore: How to insert multiple records in a table that has an hstore columnRails3:Postgres Hstore:如何在具有 hstore 列的表中插入多条记录
【发布时间】:2019-12-16 13:26:52
【问题描述】:

我想在具有 Hstore 列的表中插入多条记录。 我怎样才能做到这一点? col3: hstore 数据类型

INSERT INTO my_table (col1, col2, col3) VALUES ("abc",123,'"property1"=>"hello","property2"=>"hi"'), ("xyz",345,'"property1"=>"hello1","property"=>"hi1"'), ("weq",23,'"property1"=>"hello2","property"=>"hi2"')

此格式以字符串格式添加 hstore 中的记录。我希望它像我可以访问的键:值哈希

【问题讨论】:

    标签: sql ruby-on-rails postgresql hstore


    【解决方案1】:

    该 SQL 有两个问题:

    1. SQL 字符串文字用单引号括起来,双引号用于标识符(例如表名和列名)。
    2. hstore literals 不要使用大括号,它们通常表示为字符串。

    解决这些问题给我们:

    INSERT INTO my_table (col1, col2, col3) VALUES
    ('abc', 123, '"property1"=>"hello","property2"=>"hi"'),
    ('xyz', 345, '"property1"=>"hello1","property"=>"hi1"'),
    ('wqe', 23,  '"property1"=>"hello2","property"=>"hi2"')
    

    【讨论】:

    • 如果我使用它,我如何访问 hstore 值?
    • 不确定您的意思,您可以像使用 ActiveRecord 的任何其他列一样访问它们(假设 Rails 标记是正确的)。如果您不使用 Rails,那么您将使用 PostgreSQL 文档中介绍的函数。
    【解决方案2】:

    就 SQL 而言,我将提供“像访问任何其他列一样访问它们”的示例,任何到 Rails 的转换都取决于您 - 我不知道。访问 hstore 中的值与访问任何独立列之间存在细微差别。由于 hstore 由键:值对组成,因此您需要为各个值指定键。其格式为:hstore_column -> 'key_name'。示例(使用上面发布的数据)

    -- select value specific key
    select col1, col2, col3 -> 'property' 
      from my_table;
    
    -- select entire hstore when value for specific key missing   
    select col3 
      from my_table
     where col3 -> 'property' is null;
    
    -- select entire row there value ends in a digit for specific key
    select * 
      from my_table
     where col3 -> 'property' ~ '.*\d$' 
    

    希望这些帮助。 '

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-25
      • 1970-01-01
      • 2015-12-20
      • 1970-01-01
      • 2014-06-29
      • 1970-01-01
      相关资源
      最近更新 更多