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

时间:2011-10-10 13:27:52

标签: sql ruby-on-rails-3 activerecord ruby-on-rails-3.1

给出一个由描述,标签和其他一些字段组成的简单模型

结果应该是:

  • 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

1 个答案:

答案 0 :(得分:-1)

最好创建附加表:

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

P.S。:为什么每个条目只有一个标签?

相关问题