[英]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.