[英]Converting a Postgres query to Rails ActiveRecord?
是否可以用Rail的ActiveRecord格式編寫以下查詢? 我嘗試了十億種不同的Arel方法,但無法獲得相同的結果。
SELECT topic_id, count(*) as total
FROM questions_topics
WHERE question_id IN (
SELECT id
FROM questions
WHERE user_id = 1000
UNION ALL
SELECT questions.id
FROM questions JOIN answers ON (questions.id = answers.question_id)
WHERE answers.user_id = 1000
)
GROUP BY topic_id
ORDER BY total DESC;
好吧,這應該工作。 並非完全相同,但應給出相同的結果。
QuestionTopic.where(
"question_id IN (?) OR question_id IN (?)",
Question.where(user_id: 1000).select(:id),
Answer.where(user_id: 1000).select(:question_id)
).group('topic_id')
.order('total desc')
.select('topic_id, count(*) as total')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.