一尘不染

使用find的Rails SQL查询

sql

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

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

我该怎么做?我正在使用Rails框架和MySQL。提前致谢。


阅读 160

收藏
2021-03-10

共1个答案

一尘不染

简单方法:

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)"])
2021-03-10