2013-07-06 73 views
3

我们正在尝试创建一个可以简化为博客示例的ActiveRecord查询,以便于理解。我们如何找到没有任何评论留下的所有博客文章?Rails - 查找所有没有任何具有特定值的子项的条目

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

回答

4

最适合的sql语法应该是“not exists”子句。外连接也很受欢迎,但这往往是出于历史原因,因为RDBMS查询优化器不擅长优化包含多条记录的查询。

如今一个体面的优化器可以impliment与不存在使用适当的如哈希反连接批量数据进行处理的查询。

查询会...

select * 
from posts 
where not exists (
     select null 
     from comments 
     where comments.post_id = posts.id and 
       comments.user_id = 38) 

在轨发言...

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

UPDATE:

在轨道更好的语法:

Post.where.not(Comment.where("comments.post_id = posts.id").where(:user_id => user.id}).exists) 
+0

这正是我们需要的!谢谢您的帮助。 –

+0

这太棒了!它应该包含在activerecord中! –

+0

这是辉煌! – saadlulu

2
Post.joins("LEFT JOIN comments ON posts.id = comments.post_id AND user_id = #{user_id}").where("comments.id IS NULL") 
相关问题