Rails/SQL:查找没有孩子或所有孩子都患有某种疾病的父母

Yas*_*ine 3 ruby sql postgresql activerecord ruby-on-rails

我需要找到没有孩子或所有孩子都患有疾病(状态 = 1)的父母。

class Parent
  has_many :children
end

class Child
  enum status: [ :confirmed, :not_confirmed ]
  belongs_to :parent
end
Run Code Online (Sandbox Code Playgroud)

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

Parent.joins(:children).where('count(children) = 0')
Run Code Online (Sandbox Code Playgroud)

铁轨回答。

Kac*_*che 6

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

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

该查询比任何需要连接的查询执行得更好,因为它将向EXPLAIN您展示 Postgres 将通过Nested Loop Anti Join操作来完成此操作。