如何在RoR ActiveRecord中使用多个JOIN和OR编写此MYSQL查询?

时间:2013-02-26 05:53:23

标签: ruby-on-rails activerecord

rails --version
2.3.16
ruby --version
1.8.7

型号:

class AToB
    belongs_to :a
    belongs_to :b
    default_scope :include => [:a, :b]
end
class A
    has_many :a_to_bs
    has_many :bs, :through => :a_to_bs
    named_scope :twos, :conditions => { :var => 2 }
    named_scope :buzzed, :conditions => { :fizz => ['buzz'] }
end
class B
    has_many :a_to_bs
    has_many :as, :through => :a_to_bs
end

MYSQL查询:

SELECT COUNT(DISTINCT a.id), COUNT(DISTINCT c.id)
FROM a_to_b
INNER JOIN a on a.id = a_to_b.a_id
INNER JOIN b on b.id = a_to_b.b_id
WHERE (a.var = 2 AND a.fizz in ('buzz') AND
       (b.foo = TRUE OR b.bar = TRUE OR (b.moo = TRUE AND a_to_b.goo = FALSE))
      )

还需要这种变化

SELECT COUNT(DISTINCT a.id), COUNT(DISTINCT c.id)
FROM a_to_b
INNER JOIN a on a.id = a_to_b.a_id
INNER JOIN b on b.id = a_to_b.b_id
WHERE (a.var = 2 AND a.fizz in ('buzz') AND
       NOT (b.foo = TRUE OR b.bar = TRUE OR (b.moo = TRUE AND a_to_b.goo = FALSE))
      )

我已经搜索了无数简单的例子,阅读rails docs等等都无济于事。

2 个答案:

答案 0 :(得分:0)

让我试着回答这个问题。例如,你的模型在Rails中如下:

#a.rb
class A < ActiveRecord::Base 
  attr_accessible :var, :fizz
  has_many :a_to_bs
end

#b.rb
class B < ActiveRecord::Base
  attr_accessible :foo, :bar, :moo
  has_many :a_to_bs
end

#a_to_b.rb
class AToB < ActiveRecord::Base
  attr_accessible :goo, :a_id, :b_id, :a, :b
  belongs_to :a
  belongs_to :b
end

第一个问题的典型查询是:

records = AToB.where("a.var = ? AND a.fizz in (?) AND (b.foo = ? OR b.bar = ? OR 
          (b.moo = ? AND a_to_b.goo = ?))", 2, 'buzz', true, true, true, false)

对于第二个,它将是:

records = AToB.where("a.var = ? AND a.fizz in (?) AND NOT (b.foo = ? OR b.bar = ? OR
         (b.moo = ? AND a_to_b.goo = ?))", 2, 'buzz', true, true, true, false)

假设您提到的查询正确无误,答案是正确的。

答案 1 :(得分:0)

这种方式有用:

scope = A.twos.buzzed
scope.count(:joins => { :b => :a_to_b }, :conditions => "b.foo = TRUE OR b.bar = TRUE OR (b.moo = TRUE AND a_to_b.goo = FALSE)")

在我确定之前要再测试一下。