7

我希望使用 find 在 rails 控制器中编写此 SQL 查询:

select id,name from questions
where id not in (select question_id from levels_questions where level_id=15)

我将如何做到这一点?我正在使用 Rails 框架和 MySQL。提前致谢。

4

3 回答 3

28
Question.find_all_by_sql('select id,name from questions where id not in (select question_id from levels_questions where level_id=15)')

这无疑是非 ActiveRecord-ish,但我发现在使用 AR 宏时,诸如此类的复杂查询往往不太清晰/高效。如果您已经构建了 SQL,那么您不妨使用它。

一些建议:将此 find 调用封装在 Question 类内部的方法中,以隐藏控制器/视图的详细信息,并考虑其他可能更有效的 SQL 构造(例如,levels_questions.question_id 为 null 的 OUTER JOIN)

于 2009-06-12T06:04:36.770 回答
21

简单的方法:

ids = LevelsQuestion.all(:select => "question_id", 
        :conditions => "level_id = 15").collect(&:question_id)
Question.all(:select => "id, name", :conditions => ["id not in (?)", ids])

一枪:

Question.all(:select => "id, name",
:conditions => ["id not in (select question_id from levels_questions where level_id=15)"])
于 2009-06-12T06:05:38.810 回答
3

和rails 3方式:

ids = LevelsQuestion.select(:question_id).where(:level_id => 15).collect(&:question_id)
Question.select(:id, :name).where("id not in (?)", ids)
于 2012-03-07T12:13:49.520 回答