2014-05-16 149 views
1

是否可以使用Rail的ActiveRecord格式編寫以下查詢?我已經嘗試了十億種與arel不同的方式,但無法獲得相同的結果。將Postgres查詢轉換爲Rails ActiveRecord?

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; 
+0

您是否有像QuestionTopic和其他相關模型? – zishe

+1

我會先將它轉換爲EXISTS(...)或EXISTS(...)形式,這可能會比UNION更有效率。 – joop

+0

也許這次演講會幫助你理解Arel:https://www.youtube.com/watch?v=ShPAxNcLm3o它解釋瞭如何將任何SQL查詢轉換爲Arel AST – Hnatt

回答

0

嗯,這應該工作。不完全一樣的東西,但應該給出相同的結果。

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')