我直接使用这个查询并想使用 ActiveRecord,
SELECT count(*)
FROM p
LEFT JOIN
(SELECT pid
FROM s LEFT JOIN i ON s.key = i.sid
WHERE i.default = 'y') AS table_x
ON p.pid = table_x.pid WHERE isnull(table_x.pid) AND p.show = 'y'
但我不太确定如何实现上述内容。我到目前为止的定义如下。
class P < ActiveRecord::Base
has_many :s, :foreign_key => 'pid'
has_many :i, :through => :s
end
class S < ActiveRecord::Base
belongs_to :p, :foreign_key => 'pid'
has_many :i, :foreign_key => 'sid'
end
class I < ActiveRecord::Base
belongs_to :s, :foreign_key => 'sid'
belongs_to :p, :through => :s
end
我很想知道的部分是关于如何创建/将子选择作为表/模型?