我正在开发一个 RoR 应用程序。我将 Postgres 与 Hstore 一起使用。我想使用group
使用 Hstore 键的查询。如何才能做到这一点?
问问题
1360 次
1 回答
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')")...
...
于 2012-12-25T20:31:47.033 回答