我希望使用 find 在 rails Controller 中编写此 SQL 查询:
select id,name from questions
where id not in (select question_id from levels_questions where level_id=15)
我将如何做到这一点?我正在使用 Rails 框架和 MySQL。
提前致谢。
最佳答案
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 类中的方法中以隐藏 Controller / View 中的详细信息,并考虑其他可能更有效的 SQL 结构(例如,Levels_questions.question_id 为 null 的 OUTER JOIN)
关于sql - 带查找功能的 Rails SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/985211/