简体   繁体   English

如何限制ActiveRecord查询,然后运行“ where”子句?

[英]How do I limit an ActiveRecord query, then run a “where” clause?

I'm trying to find responses for a survey, limiting the number of responses to the limit specified on the user's plan, then for each choice, I want to find how many responses there are. 我正在尝试查找调查的答复,将答复的数量限制为用户计划中指定的限制,然后针对每个选择,我想查找有多少答复。 My current query looks like this: 我当前的查询如下所示:

Response.joins(choice: { question: :survey })
    .where(surveys: { id:survey.id })
    .limit(plan.response_limit)
    .where(choice: object)

However, this query runs the "where" clauses, then limits the query. 但是,此查询运行“ where”子句, 然后限制查询。 Could someone please tell me how to write a query that does what I want? 有人可以告诉我如何编写符合我要求的查询吗?

Edit: 编辑:

The query I posted produces the following SQL: 我发布的查询产生以下SQL:

 SELECT  "responses".* FROM "responses" 
 INNER JOIN "choices" ON "choices"."id" = "responses"."choice_id" 
 INNER JOIN "questions" ON "questions"."id" = "choices"."question_id" 
 INNER JOIN "surveys" ON "surveys"."id" = "questions"."survey_id" 
 WHERE "surveys"."id" = 1 AND "responses"."choice_id" = 1 
 LIMIT 5000

Edit 2: SQL formatting 编辑2:SQL格式

You can use the from method to SELECT from a subquery: 您可以使用from方法从子查询中进行SELECT:

subquery = Response.joins(choice: { question: :survey })
  .where(surveys: { id:survey.id })
  .limit(plan.response_limit)

responses = Response.from(subquery, :resp)
  .where(choice: object)

I'm not 100% sure how Rails deals with subqueries behind the scenes, so you might have to tweak that into something like this instead: 我不是100%不确定Rails如何处理后台的子查询,因此您可能不得不将其调整为类似以下内容:

responses = Response.from(subquery)
  .where("resp.choice_id = ?", object)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在SQL Developer的查询的WHERE子句中使用unicode? - How do I use unicode in the WHERE clause of a query in SQL Developer? 如何在SQL查询where子句中指定多个值? - How do I specify multiple values in SQL query where clause? 如何在参数化 SQL 查询中使用多个 WHERE 子句? - How do I use multiple WHERE clause in parameterized SQL query? 在以下查询中,如何在where子句中使用“ group”进行比较? - How do I use the `group` in where clause for the comparison in following query? 如何在查询中添加 WHERE 子句以避免出现“WHERE 子句中的未知列”错误? - How do I add a WHERE clause to my query to avoid the 'unknown column in WHERE clause' error? 如何使WHERE子句中的IN查询更快地运行 - How to make Query with IN in WHERE clause run faster 如何在此查询中运行GROUP BY子句? - How do I make the GROUP BY clause in this query run? 如何在SQL Server查询的WHERE子句中强制OR子句在另一个子句上? - How do I force an OR clause over another in a WHERE clause in a query in SQL Server? Android Room SQL 查询 - 如何使用条件 WHERE 子句运行查询 - Android Room SQL Query - How can I run a query with a conditional WHERE clause 如何将此SQL转换为ActiveRecord查询? - How do I turn this SQL into an ActiveRecord query?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM