我试图找到一种方法来查询如何通过多个唯一字段查找项目。所以例如我想找到这个项目,其中"国家"和"城市"是独一无二的。
对于我一直在使用的单个字段:
@foo = Foo.where(created_at: from..to).to_a.uniq{ |foo| foo.bar }
其中bar
是我Foo
表中的唯一字段。
如何Foo
bar
和baz
字段是唯一的?
答案 0 :(得分:2)
您可以将unique
方法与数组一起用作return:
@foo = Foo.where(created_at: from..to).to_a.uniq{ |foo| [foo.bar, foo.baz] }
答案 1 :(得分:1)
请使用DISTINCT ON
Foo.where(created_at: from..to)
.select("DISTINCT ON (foo) foo, bar")
.order("foo, bar")
这是一个示例,显示此查询如何在多列上提供唯一记录。让我们创建一个表:
app_development=# select * from clients;
id | age | name | created_at | updated_at
----+-----+------+----------------------------+----------------------------
1 | 26 | Arup | 2015-03-23 08:56:45.968966 | 2015-03-23 08:56:45.968966
2 | 26 | Arup | 2015-03-23 08:56:57.269637 | 2015-03-23 08:56:57.269637
3 | 25 | Ayan | 2015-03-23 08:57:06.956179 | 2015-03-23 08:57:06.956179
(3 rows)
appdevelopment=# SELECT DISTINCT ON (name) name, age FROM "clients" ORDER BY name, age;
name | age
------+-----
Arup | 26
Ayan | 25
(2 rows)
你也可以在Rails中完全相同:
2.1.2 :005 > Client.select("DISTINCT ON (name) name, age").order("name, age")
Client Load (0.9ms) SELECT DISTINCT ON (name) name, age FROM "clients" ORDER BY name, age
=> #<ActiveRecord::Relation [#<Client id: nil, age: 26, name: "Arup">, #<Client id: nil, age: 25, name: "Ayan">]>
2.1.2 :006 > Client.select("DISTINCT ON (name) name, age").order("name, age").map { |r| [r.name, r.age] }
Client Load (0.5ms) SELECT DISTINCT ON (name) name, age FROM "clients" ORDER BY name, age
=> [["Arup", 26], ["Ayan", 25]]