gpt4 book ai didi

ruby-on-rails - 内部联接上的 Rails ActiveRecord 子查询

转载 作者:行者123 更新时间:2023-12-04 05:56:25 26 4
gpt4 key购买 nike

我正在努力使用 Rails 的 ActiveRecord 查询接口(interface)来复制具有内部联接子查询的查询。我将如何复制以下内容:

SELECT ass.name, COUNT(DISTINCT a.question_id) AS 
answered_questions, tq.total_questions
FROM assessments AS ass
INNER JOIN (SELECT ass.id, COUNT(q.id) AS total_questions FROM
questions AS q INNER JOIN assessments AS ass ON ass.id=q.assessment_id
GROUP BY
ass.id) as tq ON tq.id=ass.id
INNER JOIN questions AS q ON q.assessment_id=ass.id
INNER JOIN answers AS a ON a.assessment_id=ass.id AND a.question_id=q.id
INNER JOIN org_assesments AS oa ON ass.id=oa.assessment_id
INNER JOIN users AS u ON oa.org_id=u.org_id AND
a.user_id=u.id
WHERE u.id=1
GROUP BY ass.name, tq.total_questions
ORDER BY ass.created_at DESC
LIMIT 10

我似乎无法使用查询生成器使其与子查询一起使用。如果没有子查询,我有这个,它可以为我提供评估标题和回答的问题数量:

Question.joins(:assessment => {:org_assessments => {:org => :users}}).joins(:answers)
.where(answers:{:user_id => params[:id]})
.distinct('answers.question_id').group(['assessments.name']).count()

我怎样才能像上面的原始 SQL 那样编写这个来包含子查询?

最佳答案

您可以将子查询作为字符串发送到 joins 方法:

subquery =
TotalQuestion.
joins(:assessments).
group('assessments.id').
select('assessments.id, COUNT(q.id) as total_questions').to_sql

Question.joins("(#{sub_query}) as tq on tq.id=ass.id")

您可以将它与查询的其他部分结合起来:

Question.
joins(:assessment => {:org_assessments => {:org => :users}}).joins(:answers).
joins("(#{sub_query}) as tq on tq.id=ass.id").
where(answers:{:user_id => params[:id]}).
distinct('answers.question_id').group(['assessments.name']).count()

关于ruby-on-rails - 内部联接上的 Rails ActiveRecord 子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44283756/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com