简体   繁体   English

将Postgres查询转换为Rails ActiveRecord吗?

[英]Converting a Postgres query to Rails ActiveRecord?

Is it possible to write the following query in Rail's ActiveRecord format? 是否可以用Rail的ActiveRecord格式编写以下查询? I've tried a billion different ways with arel but can't get the same results. 我尝试了十亿种不同的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;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM