【问题标题】:Questions without any answer from an user没有任何用户回答的问题
【发布时间】:2021-05-05 15:08:34
【问题描述】:

我有一个questions 表、一个user 表和一个answers 表,其中user_id 和question_id 作为外键。

我试过了:

select questions.title from questions
full outer join answers on answers.question_id = questions.id
where answers.user_id = 1
group by questions.id
having count(answers.id) = 0

但问题是,当 questions.id 为 null 时,它按 null 分组

理想情况下,查询应该可以使用 ActiveRecord (Ruby on Rails)。

【问题讨论】:

  • 为什么不使用 ActiveRecord 而不是 SQL 来表达这一点?
  • when questions.id is null it groups by null - 为什么你的主键列可以为空?
  • @tadman 我想让问题更通用,以便有更多机会得到答案,模型很明显,三个类,两个belongs_to 和两个has_many
  • @max 也许我的假设是错误的,我只知道它返回了错误的结果
  • 很公平,但是如果您利用模型中的关系,其中很多确实会转化为 ActiveRecord。

标签: sql ruby-on-rails


【解决方案1】:

如果您希望问题没有答案,请使用LEFT JOIN:

select q.title
from questions q left join
     answers a
     on a.question_id = q.id and a.user_id = 1
where a.question_id is null;

一些注意事项:

  • 不需要聚合。
  • 您正在寻找不匹配项。使用LEFT JOIN,只需检查是否没有不匹配项。
  • 带有WHERE 子句的FULL JOIN 确实有点难以解释。但本质上,您将获得user_id = 1 的所有答案以及所有其他用户的问题。

【讨论】:

  • 为什么我不能把a.user_id = 1 放在where 中?
  • @Dorian 。 . .你可以做到这一点。它只是把外连接变成内连接,所以查询不会做你想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多