Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql Postgres hstore查询在Rails中返回多个值_Sql_Ruby On Rails_Ruby_Rails Postgresql_Hstore - Fatal编程技术网

Sql Postgres hstore查询在Rails中返回多个值

Sql Postgres hstore查询在Rails中返回多个值,sql,ruby-on-rails,ruby,rails-postgresql,hstore,Sql,Ruby On Rails,Ruby,Rails Postgresql,Hstore,我正在与Ruby on Rails一起使用这些宝石: gem "pg", "~> 0.15.1" gem "postgres_ext", "~> 0.3.0" gem "activerecord-postgres-hstore", "~> 0.7.6" 一个活动记录解决方案会更好,但是一个严格的sql答案会起作用 我有一个carts表,表中有items hstore列。此列中的一个示例条目是

我正在与Ruby on Rails一起使用这些宝石:

gem "pg",                           "~> 0.15.1"
gem "postgres_ext",                 "~> 0.3.0"
gem "activerecord-postgres-hstore", "~> 0.7.6" 
一个活动记录解决方案会更好,但是一个严格的sql答案会起作用

我有一个carts表,表中有items hstore列。此列中的一个示例条目是:

{"1614"=>{:quantity=>"100"}, "1938"=>{:quantity=>"50"}, "1614"=>{:quantity=>"50"}, "1983"=>{:quantity=>"100"}, "1322"=>{:quantity=>"10"}, "1691"=>{:quantity=>"25"}, "1734"=>{:quantity=>"20"}}
您会注意到散列中有一个重复的id(1614),但其数量不同

我想写一个查询,它将返回一个带有项目id计数和总数量的表。应该是这样的:

 item_id | count | total 
---------+-------+------
   1614  |   2   |  150
   1938  |   1   |  50
   1983  |   1   |  50
   1322  |   1   |  100
以下是我正在处理的查询:

SELECT  
skeys(carts.items) as item_ids,
COUNT(*) AS count,
svals(carts.items) as items
FROM carts
GROUP BY
skeys(carts.items),
svals(carts.items)
它返回:

 item_id | count | total 
---------+-------+------
   1614  |   2   |  {:quantity=>"150"}
   1938  |   1   |  {:quantity=>"50"}
   1983  |   1   |  {:quantity=>"50"}
   1322  |   1   |  {:quantity=>"100"}

什么是表模式?您确定
项目
是hstore吗?谢谢。该字段是一个文本字段。我已经删除了问题中的错误。因此,它实际上不是一个hstore列,而现在您手中有一堆混乱的字符串化数据?不。由于迁移,它现在是一个hstore列。hstore是扁平的,没有嵌套。看起来您的数据库中出现了字符串化哈希。