Rails-查找没有任何子项具有特定值的所有条目

Mat*_*ton 4 activerecord ruby-on-rails

为了理解起见,我们正在尝试创建一个ActiveRecord查询,该查询可以简化为博客示例。我们如何查找所有特定用户没有评论的博客文章?

只要某些评论不是由特定用户撰写的,我们当前的查询就会返回帖子,但是,如果任何评论是由该用户撰写的,则我们需要排除该博客帖子。有任何想法吗?

Dav*_*dge 6

最合适的sql语法是“不存在”子句。外部联接也很流行,但这往往是出于历史原因,因为RDBMS查询优化器过去并不擅长针对涉及许多记录的查询优化它们。

如今,体面的优化器可以使用诸如散装数据的哈希反联接之类的适当内容来暗含不存在的查询。

查询将是...

select *
from   posts
where  not exists (
         select null
         from   comments
         where  comments.post_id = posts.id and
                comments.user_id = 38)
Run Code Online (Sandbox Code Playgroud)

在铁轨说话...

Post.where("not exists (select null from comments where comments.post_id = posts.id and comments.user_id = #{user.id}")
Run Code Online (Sandbox Code Playgroud)

更新:

Rails中更好的语法:

Post.where.not(Comment.where("comments.post_id = posts.id").where(:user_id => user.id)).exists)
Run Code Online (Sandbox Code Playgroud)