簡體   English   中英

高效查詢不同的計數和兩列分組

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

給定一個簡單的模型,該模型包含描述,標簽和其他一些字段

結果應為:

  • Entry.all中所有標簽的列表,沒有重復(例如Entry.select(“ DISTINCT(tag)”)))

  • 每個標簽重復的數量,也用於對標簽進行排序

  • 每個標簽的所有描述均按字母順序排序,再次沒有重復(但是,使用不同的標簽可以存在完全相同的描述)

是否可以將其合並為一個(有效的)查詢?

編輯:

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

最好創建其他表:

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

然后只需打電話給他們:

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

之后,您將在對象中具有所有描述:

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

PS:為什么每個條目只有一個標簽?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM