简体   繁体   English

rails 4 在 postgres 的多列上选择不同的地方和限制

[英]rails 4 select distinct on multiple columns in postgres with where and limit

How do you select multiple fields with distinct values, and other non-distinct fields with them, all in one call with where and limit?您如何选择具有不同值的多个字段以及其他具有不同值的字段,所有这些都在一次调用中使用 where 和 limit? I tried .pluck (which supports multiple fields in rails 4), .uniq (which didn't work in my case).我尝试了 .pluck(它支持 rails 4 中的多个字段)、.uniq(在我的情况下不起作用)。

This is what worked for me, when used in the controller action在控制器操作中使用时,这对我有用

@models = Model.select('DISTINCT ON (field1,field2,field3) *')
     .where(id: params[:id])
     .limit(100)

这里有一个不那么冗长、更以 ActiveRecord 为中心的方法,它不仅适用于 Postgres,也适用于 MySQL。

Model.select('field1,field2').distinct.where(field3: 'value').limit(10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM