首页 > 解决方案 > Rails / SQL:查找没有孩子或所有孩子都有条件的父母

问题描述

我需要找到没有孩子或所有孩子都完全有条件的父母(状态 = 1)。

class Parent
  has_many :children
end

class Child
  enum status: [ :confirmed, :not_confirmed ]
  belongs_to :parent
end

我知道第一部分,即寻找没有孩子的父母。

Parent.joins(:children).where('count(children) = 0')

铁轨回答。

标签: sqlruby-on-railsrubypostgresqlactiverecord

解决方案


由于您使用的是 Postgres,因此您可以使用NOT EXISTS查询:

# Parents with no children
Parent.where.not('exists (?)', Child.where('children.parent_id = parents.id').select(1))

这个查询比任何需要连接的查询执行得更好,因为它EXPLAIN会告诉你 Postgres 将通过一个Nested Loop Anti Join操作来完成这个。


推荐阅读