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

haf*_*tim 3 postgresql activerecord ruby-on-rails hstore rails-activerecord

我正在研究RoR应用程序.我使用Postgres和Hstore.我想使用groupHstore密钥使用查询.如何才能做到这一点?

mu *_*ort 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
Run Code Online (Sandbox Code Playgroud)

您可以使用h -> key以下内容按键值进行分组:

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

请注意,缺少的键和NULL值最终在这里显示相同.您甚至可以使用exist以下方法对密钥进行分组:

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

你不会想要,group by (h -> 'a') is not null因为你可以有NULL值,该测试不会区分显式NULL和没有相关密钥的hstore; 当然,这可能是你想要的,所以也许你想要分组(h -> 'a') is not null.

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

Model.group("h -> 'a'")...
Model.group("exist(h, 'a')")...
...
Run Code Online (Sandbox Code Playgroud)