我有一张这样的桌子:
table: searches
+------------------------------+
| id | address | date |
+------------------------------+
| 1 | 123 foo st | 03/01/13 |
| 2 | 123 foo st | 03/02/13 |
| 3 | 456 foo st | 03/02/13 |
| 4 | 567 foo st | 03/01/13 |
| 5 | 456 foo st | 03/01/13 |
| 6 | 567 foo st | 03/01/13 |
+------------------------------+
并想要一个这样的结果集:
+------------------------------+
| id | address | date |
+------------------------------+
| 2 | 123 foo st | 03/02/13 |
| 3 | 456 foo st | 03/02/13 |
| 4 | 567 foo st | 03/01/13 |
+------------------------------+
但是 ActiveRecord 似乎无法达到这个结果。这是我正在尝试的:
- 模型有一个 'most_recent' 范围:
scope :most_recent, order('date_searched DESC')
Model.most_recent.uniq
返回完整集(SELECT DISTINCT "searches".* FROM "searches" ORDER BY date DESC
)——显然查询不会做我想要的,但也不会只选择一列。我需要所有列,但只需要address
结果集中唯一的行。- 我可以做类似的事情
Model.select('distinct(address), date, id')
,但感觉......错了。