我有一个模型,ConnectedUser
,它属于其他 2 个模型User
和Station
。
这是一个简单的模型,只有这些关系和一个布尔active
。
我的目标查询结果只是每个User
的每个最新ConnectedUser
记录(其中Station
是特定 ID)。
例如,如果我的ConnectedUser
表看起来像这样...
+----+---------+------------+--------+------------+
| id | user_id | station_id | active | created_at |
+----+---------+------------+--------+------------+
| 1 | 1 | 1 | true | 20 June |
| 2 | 1 | 1 | false | 19 June |
| 3 | 1 | 2 | false | 20 June |
| 4 | 2 | 1 | false | 18 June |
| 5 | 2 | 1 | false | 21 June |
+----+---------+------------+--------+------------+
该站是 id 为 1 的电台,那么我希望查询返回......
[
<ConnectedUser id: 1, user_id: 1, station_id: 1, active: true, created_at: "2019-06-20">,
<ConnectedUser id: 5, user_id: 2, station_id: 1, active: false, created_at: "2019-06-21">
]
为了实现这一目标,我一直在尝试使用group
来order
ConnectedUser.where(station: station).select(:user_id).group(:user_id).order(:created_at)
但是不断收到这样的错误:
活动记录::语句无效 (PG::分组错误: 错误: 列 "connected_users.created_at"必须出现在 GROUP BY 子句中,或者 在聚合函数中使用)
我无法获得特定的ConnectedUser
id,所以感觉我错过了一些重要的理解,如何使用group
和聚合结果。
这在一个活动记录查询中可能吗?
非常感谢。
在Postgres中,如果您想要每个用户/电台的最新版本,我建议您distinct on
:
select distinct on (station_id, user_id) cu.*
from ConnectedUser cu
order by station_id, user_id, created_at desc;
你应该使用DISTINCT ON
而不是GROUP
。以下是在 Rails 中执行此操作的方法:
ConnectedUser.select("DISTINCT ON (station_id, user_id) *")
.where(station_id: params[:station_id])
.order(created_at: :desc)
当然,params[:station_id]
是您想要过滤的内容
可能,这将解决它
ConnectedUser.where(active: true).order(user_id: :desc).uniq(&:user_id)
order
用于对user_id
字段进行排序DESC
在此解决方案上,我使用的是uniq
,这是一个阵列解决方案,将仅选择最新的user_id
编辑:
我错了,uniq 没有按预期工作,但在这里测试,我发现:
ConnectedUser.where(active: true).order(created_at: :desc).group(:user_id)
看起来很像你的,但是,当你使用选择时,它确实只选择字段user_id,所以,你不能按created_at
排序
应该工作