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;
您是否有像QuestionTopic和其他相關模型? – zishe
我會先將它轉換爲EXISTS(...)或EXISTS(...)形式,這可能會比UNION更有效率。 – joop
也許這次演講會幫助你理解Arel:https://www.youtube.com/watch?v=ShPAxNcLm3o它解釋瞭如何將任何SQL查詢轉換爲Arel AST – Hnatt