ruby-on-rails - 如何使用 Hstore 键在 ActiveRecord 查询上使用 group by 子句?

标签 ruby-on-rails postgresql activerecord rails-activerecord hstore

<分区>

我正在处理 RoR 应用程序。我将 Postgres 与 Hstore 一起使用。我想使用一个使用 Hstore 键的 group 查询。如何做到这一点?

最佳答案

是的,当然可以。 GROUP BY 子句是一个非常通用的工具,因此您可以按您喜欢的任何表达式进行分组。所以,给定这样的数据:

=> select * from with_hstore order by id;
 id |         h          
----+--------------------
  1 | "a"=>"6"
  2 | "a"=>"2"
  3 | "b"=>"1"
  4 | "a"=>"b"
  5 | "x"=>"z", "y"=>"6"
  6 | "a"=>NULL

您可以使用 h -> key 按键值分组:

=> select h -> 'a', count(*) from with_hstore group by h -> 'a';
 ?column? | count 
----------+-------
          |     3
 2        |     1
 6        |     1
 b        |     1

请注意,丢失的键和 NULL 值最终会在这里出现相同的结果。您甚至可以使用 exist 根据键的存在进行分组:

=> select exist(h, 'a'), count(*) from with_hstore group by exist(h, 'a');
 exist | count 
-------+-------
 f     |     2
 t     |     4

你不会想要 group by (h -> 'a') is not null 虽然你可以有 NULL 值,但该测试不会区分显式 NULL 和 hstore没有问题的 key ;当然,这可能是您想要的,所以您可能确实希望按 (h -> 'a') is not null 进行分组。

ActiveRecord 将允许您通过将分组条件作为 SQL 片段传递来按数据库可以处理的任何内容进行分组:

Model.group("h -> 'a'")...
Model.group("exist(h, 'a')")...
...

关于ruby-on-rails - 如何使用 Hstore 键在 ActiveRecord 查询上使用 group by 子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14033165/

相关文章:

postgresql - 创建引用不存在的表或列的 SQL 函数(尚)

postgresql - 在 PostgreSQL 中将一个数据库镜像到另一个数据库

ruby-on-rails - rails 范围内的时区独立到期日比较

mysql - 在派生表上使用复杂联接的 Active Record 查询?

ruby-on-rails - Rails 嵌套 N+1 查询问题

postgresql - 如何从 PostgreSQL 向 RabbitMQ 发送消息?

ruby-on-rails - HTTPBadRequest {"error_description": "Code has expired", "error": "invalid_grant"} for Oauth authentification, Rails 上的 ruby

sql - ActiveRecord has_many 通过多态 has_many

sql - 查找任何 3 个公共(public)属性的重复记录

javascript - 预编译rails-3 Assets 管道,使javascript失败,阻止heroku部署