Rails SQL查询与find
我希望使用find在rails控制器中编写这个SQL查询:
select id,name from questions where id not in (select question_id from levels_questions where level_id=15)
我该怎么做? 我正在使用Rails框架和MySQL。 提前致谢。
简单方法:
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)"])
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,那么您也可以使用它。
一些建议:将此查找调用封装在INSIDE Question类中的方法中,以隐藏控制器/视图中的详细信息,并考虑可能更高效的其他SQL构造(例如,其中levels_questions.question_id为null的OUTER JOIN)
和轨道3方式:
ids = LevelsQuestion.select(:question_id).where(:level_id => 15).collect(&:question_id) Question.select(:id, :name).where("id not in (?)", ids)