简体   繁体   English

从数据库获取唯一列结果的列表

[英]Get list of unique column results from database

I've stumbled across this answer and it has helped me to generate a list of unique values exactly as I wanted, however, I don't want all of the results. 我偶然发现了这个答案 ,它帮助我生成了我想要的唯一值列表,但是,我并不需要所有结果。 Is there any way to filter the results within the select or another way to accomplish this? 有没有什么方法可以过滤select的结果,或者有其他方法可以做到这一点?

I was thinking of something along the lines of this: 我在想一些类似的事情:

@results = MyModel.select("DISTINCT(columnForDistinction)", :myBoolean => false)

or 要么

@results = MyModel.select("DISTINCT(columnForDistinction)", :someString => stringImLookingFor)

Currently, I'm not able to filter the results on the query, so I am iterating over the returned array and only listing the results that have that boolean set to false like so: 目前,我无法在查询中过滤结果,因此我遍历返回的数组,仅列出将boolean设置为false的结果,如下所示:

<% @results.each do |result| %>
  <% if !result.myBoolean %>
    #do stuff here
  <% end %>
<% end %>

and

<% @results.each do |result| %>
  <% if result.someString == stringImLookingFor %>
    #do stuff here
  <% end %>
<% end %>

Is there a better way to be doing this? 有没有更好的方法可以做到这一点?

ActiveRecord query methods are chainable. ActiveRecord查询方法是可链接的。 You can call multiple and it will build them all into a query when you use the result. 您可以调用多个,并在使用结果时将它们全部构建到查询中。 For conditions, you'll use where . 对于条件,您将使用where Try something like: 尝试类似:

@results = MyModel.select("DISTINCT(columnForDistinction)").where(:myBoolean => false)

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

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