【发布时间】:2014-09-24 19:17:44
【问题描述】:
我有一个表 orders 与 id 和 color 列,id 是唯一列。
| id | color |
| ---- | ----- |
| 1 | Red |
| 2 | Red |
| 3 | Green |
| 4 | Green |
| 5 | Blue |
| 6 | Blue |
我希望在他们的color组中得到最大id的所有行,查询结果应该是
| 2 | Red |
| 4 | Green |
| 6 | Blue |
如何使用 Sqlite3(开发环境)和 PostgreSQL 9.3(生产环境)在 Rails 环境中查询正确结果
谢谢。
【问题讨论】:
-
这是
DISTINCT ON的完美用例:Order.select('DISTINCT ON (color) *').order('color, id DESC') -
@MrYoshiji,谢谢你的回答。看来我没有得到正确的结果。我应该用你的 query+.size 和
Order.group(:color).length得到相同的计数,对吧? -
@CloudBSD
Order.group(:color).count
标签: sql ruby-on-rails postgresql sqlite ruby-on-rails-4.1