如何使用Hstore密钥对ActiveRecord查询使用group by子句?

时间:2012-12-25 18:46:21

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

我正在开发一个RoR应用程序。我使用Postgres和Hstore。我想使用Hstore密钥使用group查询。怎么办呢?

1 个答案:

答案 0 :(得分:12)

是的,当然可以。 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;当然,这可能是你想要的,所以也许你想要按(h -> 'a') is not null分组。

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

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