【问题标题】:Efficient query for distinct count and group with two columns使用两列对不同计数和组进行有效查询
【发布时间】:2011-10-10 13:27:51
【问题描述】:

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

结果应该是:

  • 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

【问题讨论】:

  • 请问您可以在问题中包含表结构吗?
  • 我已经在第一行提到了那些,现在包括...
  • 描述栏的标准是什么?在你的模型中,同名的标签可以有不同的描述。
  • 是的,没错。描述不是标签的描述;)
  • 好的,但我的问题仍然存在。我们选择带有计数的 uniq 标签 (select tag, count(tag) as total from entries group by tag) - 没关系。现在我们需要在结果中添加“描述”列。例如,我们有三个相似的标签和三个不同的描述,分组后我们有一个标签,你需要什么描述?唯一的想法是 select tag, count(tag) as total, min(description) as description from entries group by tag 或在 AR 中:Entry.all(:select => 'tag, count(tag) as total, min(description) as description', :group => 'tag')

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


【解决方案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.:为什么每个条目只有一个标签?

【讨论】:

  • 在这个特定的设置中,表和数据库存在,没有选项可以创建一个单独的表。其次,描述不描述标签,它们并不真正相关。将标签视为一个类别,将描述视为对该类别中特定条目的描述。
猜你喜欢
  • 2017-03-05
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-24
  • 2011-08-17
相关资源
最近更新 更多