简体   繁体   English

高效查询不同的计数和两列分组

[英]Efficient query for distinct count and group with two columns

Given a simple model that consists of descriptions, tags, and some other fields 给定一个简单的模型,该模型包含描述,标签和其他一些字段

The results should be: 结果应为:

  • a list of all tags in Entry.all without duplicates (eg Entry.select("DISTINCT(tag)") ) Entry.all中所有标签的列表,没有重复(例如Entry.select(“ DISTINCT(tag)”)))

  • the number of duplicates for each tag, also used to sort tags 每个标签重复的数量,也用于对标签进行排序

  • all descriptions for each tag sorted alphabetically, again without duplicates (however, the exactly same description can exist with a different tag) 每个标签的所有描述均按字母顺序排序,再次没有重复(但是,使用不同的标签可以存在完全相同的描述)

Is it possible to combine this in one (efficient) query? 是否可以将其合并为一个(有效的)查询?

Edit: 编辑:

def change
  create_table :entries do |t|
    t.datetime :datum, :null => false                            
    t.string :description                                        
    t.string :tag                                                
    (and some others)
  end

  add_index :entries, :user_id
end

It's better to create additional table: 最好创建其他表:

rails g model Tag name:string description:string
rails g model Entry tag:references ...

And then just call them: 然后只需打电话给他们:

@entries = Entry.select('tag_id, count(tag_id) as total').group(:tag_id).includes(:tag)

After that, you will have all descriptions in your object: 之后,您将在对象中具有所有描述:

@entries.first.tag.description # description of entry tag
@entries.first.tag.total # total number of such kind of tags

PS: Why just one tag per entry? PS:为什么每个条目只有一个标签?

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

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