开发者

Efficient query for distinct count and group with two columns

开发者 https://www.devze.com 2023-04-11 19:02 出处:网络
Given a simple model that consists of descriptions, tags, and some other fields The results should be:

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 (e.g. Entry.select("DISTINCT(tag)") )

  • the number of duplicates for each tag, also used to sort tags

  • all desc开发者_开发技巧riptions 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

P.S.: Why just one tag per entry?

0

精彩评论

暂无评论...
验证码 换一张
取 消