如何按多重关系排序计数

时间:2013-07-24 10:00:09

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

我正在使用Rails 3.2.8进行开发,并希望通过多个关系计数的总和来订购模型。

有一个Doc模型,它有许多subcatrel和subinsrels,都是Relation模型(不是模型关系,名为'Relation'的模型)。

doc.rb

class Doc < ActiveRecord::Base
  has_many :denotations
  has_many :instances, :through => :denotations
  has_many :subcatrels, :class_name => 'Relation', :through => :denotations, :source => :subrels
  has_many :subinsrels, :class_name => 'Relation', :through => :instances, :source => :subrels
  scope :pmdocs, where(:sourcedb => 'PubMed')
  .
  .
end

我想通过count子流和子数据的总和来订购Doc模型。

我在下面尝试过命令范围pmdocs。

Doc.pmdocs.includes([:subcatrels, :subinsrels]).group('docs.id').order('(count(subcatrels.id) + count(subinsrels.id)) DESC')

并在下方收到错误。

PG::Error: ERROR:  missing FROM-clause entry for table "subcatrels"
LINE 1: SELECT  DISTINCT "docs".id, (count(subcatrels.id) + count(su...

: SELECT  DISTINCT "docs".id, (count(subcatrels.id) + count(subinsrels.id)) AS alias_0 FROM "docs" LEFT OUTER JOIN "denotations" ON "denotations"."doc_id" = "docs"."id" LEFT OUTER JOIN "relations" ON "relations"."subj_id" = "denotations"."id" AND "relations"."subj_type" = 'Denotation' LEFT OUTER JOIN "denotations" "denotations_docs_join" ON "denotations_docs_join"."doc_id" = "docs"."id" LEFT OUTER JOIN "instances" ON "instances"."obj_id" = "denotations_docs_join"."id" LEFT OUTER JOIN "relations" "subinsrels_docs" ON "subinsrels_docs"."subj_id" = "instances"."id" AND "subinsrels_docs"."subj_type" = 'Instance' WHERE "docs"."sourcedb" = 'PubMed' GROUP BY docs.id ORDER BY (count(subcatrels.id) + count(subinsrels.id)) DESC LIMIT 10 OFFSET 0

如何通过count子区和子类的总和来订购Doc模型?

其他型号的源代码如下。

denotation.rb

class Denotation < ActiveRecord::Base
  belongs_to :doc
  has_many :instances, :foreign_key => "obj_id", :dependent => :destroy
  has_many :subrels, :class_name => 'Relation', :as => :subj, :dependent => :destroy
  has_many :objrels, :class_name => 'Relation', :as => :obj, :dependent => :destroy
  .
  .
end

instance.rb

class Instance < ActiveRecord::Base
  belongs_to :obj, :class_name => 'Denotation'
  has_many :subrels, :class_name => 'Relation', :as => :subj, :dependent => :destroy
  has_many :objrels, :class_name => 'Relation', :as => :obj, :dependent => :destroy
  .
  .
end

关联图片 enter image description here

1 个答案:

答案 0 :(得分:0)

如果subinsrels.id中的WHERE不是表名,则不能要求{{1}}!