我在模型 Organizer 和 Event 之间建立了一对多的关系。
我想获得最近更新了事件的五个组织者。
Event.order('updated_at asc').
where(organizer_id: [1,2,3,4,5,6,7,8,9]).
select(:organizer_id).uniq.limit(5)
上面的代码在 SQLite3 中运行良好,但在 PostgreSQL 中的 Heroku 上抛出以下错误:
for SELECT DISTINCT, ORDER BY expressions must appear in select list
如何使查询在 PG 中工作,例如使用错误消息中建议的方法?
如果可能的话,我更希望有一个尽可能多的 ActiveRecord 而不是纯 SQL 的解决方案。
最佳答案
您通过 updated_at
订购,但只选择了 organizer_id
。 Postgres 要求 ORDER 子句中使用的字段位于 SELECT 子句中。您需要将 updated_at
添加到您的 select
列表中。
在 SQL 中,现在您有:
SELECT organizer_id FROM events WHERE ... ORDER BY updated_at asc;
你需要:
SELECT organizer_id, updated_at FROM events WHERE ... ORDER BY updated_at asc;
关于ruby-on-rails - 在 PostgreSQL 中使用 .select、.uniq 和 .order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17684392/