3
我正在处理RoR应用程序。我用Hstore使用Postgres。我想使用一个使用Hstore密钥的group
查询。如何才能做到这一点?如何在使用Hstore密钥的ActiveRecord查询上使用group by子句?
我正在处理RoR应用程序。我用Hstore使用Postgres。我想使用一个使用Hstore密钥的group
查询。如何才能做到这一点?如何在使用Hstore密钥的ActiveRecord查询上使用group by子句?
是的,当然可以。一个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
注意,一个缺少键和空值会在这里结束出来一样。你甚至可以通过一键存在使用组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')")...
...
你能和你想要做什么更多的细节解释一下吗? –