Converting a Postgres query to Rails ActiveRecord?

此生再无相见时 提交于 2020-01-03 02:00:08

问题


Is it possible to write the following query in Rail's ActiveRecord format? I've tried a billion different ways with arel but can't get the same results.

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;

回答1:


Well, this should work. Not exactly the same thing but should give same results.

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


来源:https://stackoverflow.com/questions/23700169/converting-a-postgres-query-to-rails-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!