将Postgres查询转换为Rails ActiveRecord?[英] Converting a Postgres query to Rails ActiveRecord?

本文是小编为大家收集整理的关于将Postgres查询转换为Rails ActiveRecord?的处理方法,想解了将Postgres查询转换为Rails ActiveRecord?的问题怎么解决?将Postgres查询转换为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')

本文地址:https://www.itbaoku.cn/post/1764209.html