我正在努力使用Rails的ActiveRecord查询接口来复制具有内部联接子查询的查询。我将如何复制以下内容:
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中的子查询?
答案 0 :(得分:5)
您可以将子查询作为字符串发送到joins
方法:
subquery =
TotalQuestion.
join(: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()