简体   繁体   中英

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)") )

  • 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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